PHP 实现装饰器模式

1,979 阅读1分钟

装饰器模式
角色分析
1、抽象构件角色
定义一个对象接口,以规范准备接受附件职责的对象,从而可以给这些对象动态的添加职责 2、具体构件角色
定义一个即将要接受附加职责的类 3、装饰角色
持有一个纸箱Componnet对象的指针,并定义一个与Component接口一致的接口。 4、具体装饰角色
负责给构件对象增加附加的职责。

<?php
//抽象构件角色
interface Component
{
    public function operation();
}

//具体构件角色
class ConcreComponent implements Component
{
    public function operation()
    {
        echo "Concrete Component operation";
    }
}

//装饰角色
abstract class Decorator implements Component
{
    protected $_component;

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

    public function operation()
    {
        $this->_component->operation();
    }
}

//具体装饰角色
class ConcreteDecoratorA extends Decorator
{
    public function __construct(Component $component)
    {
        parent::__construct($component);
    }

    public function operation()
    {
        parent::operation(); // TODO: Change the autogenerated stub
        $this->addOperationA();
    }

    public function addOperationA()
    {
        echo "add operation A";
    }
}

class ConcreteDecoratorB extends Decorator
{
    public function __construct(Component $component)
    {
        parent::__construct($component);
    }

    public function operation()
    {
        parent::operation(); // TODO: Change the autogenerated stub
        $this->addOperationB();
    }

    public function addOperationB()
    {
        echo "add operation B";
    }
}

$component = new ConcreComponent();
$decoratorA = new ConcreteDecoratorA($component);
$decoratorB = new ConcreteDecoratorB($component);
$decoratorA->operation();
$decoratorB->operation();
?>

一些链接: nicky-chen.github.io/2018/03/28/…