【装饰模式】遵循开闭原则,使用一个类装饰另一个类

这个设计模式,说真的,我还没读懂,读懂的兄弟可以留言帮我解释一下,我需要 慢慢的研究 这 中模式的好处,和优点,先附上我的代码

abstract class component{
    abstract public function operation();
}

class concreteComponent extends component {
    public function operation()
    {
        // TODO: Implement operation() method.
        echo '这里是具体操作';
    }
}

abstract class Decoratr extends component {
    protected $component;
    public function setComponent($component){
        $this->component = $component;
    }
    public function operation()
    {
        // TODO: Implement operation() method.
        if($this->component!=null){
            $this->component->operation();
        }
    }
}

class A extends Decoratr {
    private $state;

    public function operation()
    {
        parent::operation(); // TODO: Change the autogenerated stub
        $this->state = 'new state';
        echo '装饰A';
    }
}

class B extends Decoratr {
    public function operation()
    {
        parent::operation(); // TODO: Change the autogenerated stub
        $this->behavior();
        echo '装饰B';
    }
    public function behavior(){

    }
}

$c = new concreteComponent();
$a = new A();
$b = new B();

$a->setComponent($c);
$b->setComponent($a);
$b->operation();

看完之后,我凌乱了

相关推荐