您的当前位置:首页>全部文章>文章详情

php设计模式之装饰器模式(Decorator)

发表于:2019-08-16 10:28:46浏览:60次TAG:
装饰器模式允许我们根据运行时不同的情景动态地为某个对象调用前后添加不同的行。 ```php _component = $component; } public function operation() { $this->_component->operation(); } } // 具体装饰A class ConcreteDecoratorA extends Decorator { public function __construct(Component $component) { parent::__construct($component); } public function operation() { // 调用装饰类的操作 parent::operation(); // 新增加的操作 $this->addedOperationA(); } public function addedOperationA() { var_dump("A加点[红色]"); } } // 具体装饰B class ConcreteDecoratorB extends Decorator { public function __construct(Component $component) { parent::__construct($component); } public function operation() { // 调用装饰类的操作 parent::operation(); // 新增加的操作 $this->addedOperationB(); } public function addedOperationB() { var_dump("B加点[黄色]"); } } // 具体组件类 class ConcreteComponent implements Component { public function operation() { } } // client // 实例化一个组件 $component = new ConcreteComponent(); // 实例化 装饰A 动态调用前一个 组件 对象 $decoratorA = new ConcreteDecoratorA($component); // 实例化 装饰B 动态调用前一个 装饰A 对象,其中 装饰A 对象又调用了 组件 对象 $decoratorB = new ConcreteDecoratorB($decoratorA); $decoratorA->operation(); // 输出: // A加点[红色] var_dump("------分界线--------"); $decoratorB->operation(); // 输出: // A加点[红色] // B加点[黄色] ?> ``` 输出 ```bash vagrant@vagrant-ubuntu:~$ sudo php decorator.php string(15) "A加点[红色]" string(23) "------分界线--------" string(15) "A加点[红色]" string(15) "B加点[黄色]" ```
栏目分类全部>
腾讯云采购季云服务器一折促销