结构性模式: 装饰模式 decorator
动态地给一个对象添加一些额外的职责, 就增加功能来说, 装饰器模式相比生成子类更灵活
不改变原有的功能, 不对原有的功能加限制, 不需要原有功能对新功能提供任何帮助, 仅在原有功能上添加新的功能
- 给老系统进行升级扩展
- 不一定都是对同一个方法进行装饰,其实装饰者应该更多的用于对对象的装饰,对对象进行扩展, 增加功能方法, 削弱/减少功能方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| interface HouseBuilderInterface { public function beautify(); }
class HouseBuilder implements HouseBuilderInterface { public function beautify() { echo "粉刷完成\t"; } }
abstract class HouseBuilderDecorator implements HouseBuilderInterface { protected $houseBuilder; public function __construct(HouseBuilderInterface $houseBuilder) { $this->houseBuilder = $houseBuilder; } }
class HouseBuilderDecoratorFloor extends HouseBuilderDecorator { public function beautify() { $this->houseBuilder->beautify(); echo "铺完地板啦\t"; } }
class HouseBuilderDecoratorClean extends HouseBuilderDecorator { public function beautify() { $this->houseBuilder->beautify(); echo "打扫好啦\t"; } }
$houseBuilder = new HouseBuilder(); $houseBuilder->beautify(); echo PHP_EOL; $houseBuilder = new HouseBuilderDecoratorFloor($houseBuilder); $houseBuilder->beautify(); echo PHP_EOL; $houseBuilder = new HouseBuilderDecoratorClean($houseBuilder); $houseBuilder->beautify(); echo PHP_EOL;
$houseBuilder = new HouseBuilder(); $houseBuilder = new HouseBuilderDecoratorFloor($houseBuilder); $houseBuilder = new HouseBuilderDecoratorClean($houseBuilder); $houseBuilder->beautify(); echo PHP_EOL;
|