装饰器模式,顾名思义,就是对已经存在的某些类进行装饰,以此来扩展一些功能。其结构图以下:php
<?php /** *装饰器模式 **/ interface Component{ public function operation(); } class ConcreteComponent implements Component{ public $put_str = "具体实现类"; public function operation(){ echo $this->put_str."\n"; } public function addElement($str){ $this->put_str = $str.$this->put_str; } } abstract class Decorator implements Component{ public $comm; public function __construct(Component $comm){ $this->comm = $comm; } abstract function operation(); } class ConcreteDecoratorA extends Decorator{ public function operation(){ $this->comm->addElement("被A修饰后的"); $this->comm->operation(); } } class ConcreteDecoratorB extends Decorator{ public function operation(){ $this->comm->addElement("被B修饰后的"); $this->comm->operation(); } } $comm = new ConcreteComponent(); $comm->operation(); // 输出 “具体实现类” $decorate_a = new ConcreteDecoratorA($comm); $decorate_a->operation(); // 输出 “被A修饰后的具体实现类” $decorate_b = new ConcreteDecoratorB($comm); $decorate_b->operation(); // 输出 “被B修饰后的被A修饰后的具体实现类”
何时使用?:通常的,咱们为了扩展一个类常常使用继承方式实现,因为继承为类引入静态特征,而且随着扩展功能的增多,子类会很膨胀。在不想增长不少子类的状况下扩展类可使用这种设计模式设计模式