PHP设计模式:装饰模式

装饰模式:动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活

装饰者模式动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。

装饰模式是为已有功能动态的添加更多功能的一种方式。当系统需要新功能时,向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为。

<?php //Component是定义一个对象接口,可以给这些对象动态的添加职责 abstract class Component { public abstract function operation(); } class ConcreteComponent extends Component { public function operation() { echo '具体对象的操作:<br/>'; } } class Decorator extends Component { public $component; public function __construct($component) { $this->component = $component; } public function operation() { $this->component->operation(); } } class DecoratorA extends Decorator { public function operation() { parent::operation(); echo 'A<br/>'; } } class DecoratorB extends Decorator { public function operation() { parent::operation(); echo 'B<br/>'; } } class DecoratorC extends Decorator { public function operation() { parent::operation(); echo 'C<br/>'; } } /* * 输出结果: 具体对象的操作: A B C */ $component = new ConcreteComponent(); $a = new DecoratorA($component); $b = new DecoratorB($a); $c = new DecoratorC($b); $c->operation();
    原文作者:骆驼大笨笨
    原文地址: https://blog.csdn.net/juan083/article/details/51745896
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞