Content

PHP结构型模式之装饰器模式(php设计模型)没想到

文章摘要

本文介绍了PHP中抽象组件和装饰器的设计模式。文章通过示例展示了如何通过接口和类的继承来实现组件的扩展功能。具体来说,文章定义了抽象组件接口`Component`,并实现了两个具体的组件`ConcreteComponent`。接着,通过抽象装饰器`Decorator`实现了组件的动态装饰功能,该装饰器通过继承组件并重写`operation`方法来调用基类的`operation`方法并添加额外的行为。文章还展示了如何通过装饰器逐步装饰组件,并最终调用`operation`方法来展示装饰后的功能。

<?php // 抽象组件 interface Component { public function operation(); } // 具体组件 class ConcreteComponent implements Component { public function operation() { echo “ConcreteComponent operation.\n”; } } // 抽象装饰器 abstract class Decorator implements Component { protected $component; public function __construct(Component $component) { $this->component=$component; } public function operation() { $this->component->operation(); } } // 具体装饰器A class ConcreteDecoratorA extends Decorator { public function operation() { parent::operation(); $this->addedBehavior(); echo “ConcreteDecoratorA operation.\n”; } public function addedBehavior() { echo “Added behavior in ConcreteDecoratorA.\n”; } } // 具体装饰器B class ConcreteDecoratorB extends Decorator { public function operation() { parent::operation(); $this->addedBehavior(); echo “ConcreteDecoratorB operation.\n”; } public function addedBehavior() { echo “Added behavior in ConcreteDecoratorB.\n”; } } // 客户端代码 $component=new ConcreteComponent(); $decoratorA=new ConcreteDecoratorA($component); $decoratorB=new ConcreteDecoratorB($decoratorA); $decoratorB->operation();