学习php设计模式 php实现装饰器模式(decorator)_php技巧
动态的给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活【GOF95】 装饰模式是以对客户透明的方式动态地给一个对象附加上更多的职责。这也就是说,客户端并不会觉得对象在装饰前和装饰后有什么不同。装饰模式可以在不使用创造更多子类的情况下,将对象的功能加以扩展。 一、装饰模式结构图 二、装饰模式中主要角色 <?php/** * 抽象构件角色 */interface Component { /** * 示例方法 */ public function operation();} /** * 装饰角色 */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 __construct(Component $component) { parent::__construct($component); } public function operation() { parent::operation(); // 调用装饰类的操作 $this->addedOperationA(); // 新增加的操作 } /** * 新增加的操作A,即装饰上的功能 */ public function addedOperationA() { echo 'Add Operation A <br />'; }} /** * 具体装饰类B */class ConcreteDecoratorB extends Decorator { public function __construct(Component $component) { parent::__construct($component); } public function operation() { parent::operation(); $this->addedOperationB(); } /** * 新增加的操作B,即装饰上的功能 */ public function addedOperationB() { echo 'Add Operation B <br />'; }} /** * 具体构件 */class ConcreteComponent implements Component{ public function operation() { echo 'Concrete Component operation <br />'; } } /** * 客户端 */class Client { /** * Main program. */ public static function main() { $component = new ConcreteComponent(); $decoratorA = new ConcreteDecoratorA($component); $decoratorB = new ConcreteDecoratorB($decoratorA); $decoratorA->operation(); $decoratorB->operation(); } } Client::main();?> 以上就是使用php实现装饰模式的代码,还有一些关于装饰模式的概念区分,希望对大家的学习有所帮助。 |