动态地将责任附加到对象上,若要扩展功能,装饰者提供了比继承更有弹性的替代方案php
1.被装饰者基类(Compoent):对象组件
2.待装饰对象(ConcreteComponent):具体组件角色,即将要被装饰增长功能的类
3.装饰者基类(Decorator):须要定义一个与组件接口一致的接口,并持有一个Component对象,该对象其实就是被装饰的对象。
4.具体装饰者(ConcreteDecorator):现具体要向被装饰对象添加的功能。用来装饰具体的组件对象或者另一个具体的装饰器对象设计模式
<?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(); } } //具体装饰者类 class ConcreteComponent implements Component{ public function operation(){ return 'do operation'; } } //具体装饰者a class ConcreteDecoratorA extends Decorator{ public function __construct(Component $component) { parent::__construct($component); } public function operation() { parent::operation(); $this->addOperationA(); } public function addOperationA(){ return 'add operation a'; } } //具体装饰者类b class ConcreteDecoratorB extends Decorator{ public function __construct(Component $component) { parent::__construct($component); } public function operation() { parent::operation(); $this->addOperationB(); } public function addOperationB(){ echo 'add operation b'; } } $decoratorA = new ConcreteDecoratorA(new ConcreteComponent()); $decoratorA->operation();
1.装饰者和被装饰者对象有相同的超类型
2.你能够用一个或者多个装饰者包装一个对象
3.既然装饰者和被装饰者对象有相同的超类,因此在任何须要原始对象(被包装的)的场合,能够用装饰过的对象替换他
4.(关键点)装饰者能够在委托被装饰者的行为以前/以后,加上本身的行为,已达到特意的目的
5.对象能够在任什么时候候被装饰,因此能够在运行时动态的、不限量的用你喜欢的装饰者来装饰对象this
参考文献《head first 设计模式》spa