装饰器模式

  • 外在形式是类套类

  • 简单类递归调用

<?php
/**
 * 装饰器模式: 动态的给一个对象添加额外的职责
 * 就增加功能来说,装饰器模式比生成子类更为灵活
 */
// 组件接口
Interface Component
{
    public function operation();
}
// 具体组件实现
class ConcreteComponent implements Component
{
    public function operation()
    {
        echo "concrete_components handle\n";
    }
}

// 装饰器类
class Decorator implements Component
{
    protected $component;

    public function __construct(Component $component)
    {
        $this->component = $component;
    }
    public function operation()
    {
        $this->component->operation();
    }
}

// 装饰器A
class DecoratorA extends Decorator
{
    public function __construct(Component $comp)
    {
        parent::__construct($comp);
    }
    public function operation()
    {
        parent::operation();
        echo "it is decorator_A\n";
    }
}

// 装饰器B
class DecoratorB extends Decorator
{
    public function __construct(Component $comp)
    {
        parent::__construct($comp);
    }
    public function operation()
    {
        parent::operation();
        echo "it is decorator_B\n";
    }
}


try {
    // 不断装饰 
    // 核心在于每个类的构造方法的组件挂载(即装饰)
    $component = new ConcreteComponent();
    $a = new DecoratorA($component);
    $b = new DecoratorB($a);

    // 统一输出
    $b->operation();
} catch (Exception $e) {
    echo $e->getMessage();
}

蛇叔编程心法
16 声望1 粉丝

爱生活,爱学习,爱工作,足够拼命,足够努力。


« 上一篇
策略模式
下一篇 »
工厂方法模式