设计模式PHP版六 - 装饰器模式

    xiaoxiao2025-02-15  16

    <?php /** * 定义一个接口 * Interface Component */ interface Component { public function operation(); } /** * Class Decorator 装饰器 */ abstract class Decorator implements Component { /** * 服饰 * @var $clothing */ protected $clothing; public function __construct($clothing) { $this->clothing = $clothing; } public function operation() { $this->clothing->operation(); } } /** * Class Suit 西装装饰类 */ class Suit extends Decorator { public function __construct($clothing) { parent::__construct($clothing); } public function operation() { parent::operation(); $this->suit(); } public function suit() { echo '穿西装 '; } } /** * Class Hat 帽子装饰类 */ class Hat extends Decorator { public function __construct($clothing) { parent::__construct($clothing); } public function operation() { parent::operation(); $this->hat(); } public function hat() { echo '戴帽子 '; } } /** * Class Swimsuit 泳衣装饰类 */ class Swimsuit extends Decorator { public function __construct($clothing) { parent::__construct($clothing); } public function operation() { parent::operation(); $this->swimsuit(); } public function swimsuit() { echo '穿泳衣 '; } } /** * Class ConcreteComponent 具体组件类,要装饰的类 */ class ConcreteComponent implements Component { public function operation() { echo '裸体的人 '; } } $component = new ConcreteComponent(); $component->operation(); echo '<br>---------------------<br>'; /** * Suit继承了Decorator,当把$component传入时进入构造方法,走了parent::__construct,就是运行了父类的构造方法。 * 此时,Decorator类里的$clothing就存储了$component对象。 */ $suit = new Suit($component); // 调用时是先运行了parent::operation(),也就是Decorator类里$component对象,再调用类自身的方法 $suit->operation(); // 输出 裸体的人 穿西装 echo '<br>---------------------<br>'; /** * 同上,只不过Decorator类里的$clothing变成了Suit($component) */ $hat = new Hat($suit); // 调用时先是运行了parent::operation(),也就是Suit($component)->operation(),和上面的$suit->operation()效果是一样的 $hat->operation(); // 输出 裸体的人 穿西装 戴帽子 echo '<br>---------------------<br>'; $hatTwo = new Hat($component); $hatTwo->operation(); echo '<br>---------------------<br>'; $swimsuit = new Swimsuit($component); $swimsuit->operation(); /** * 其实就是实现了动态的对所要操作的一个很重要的类增加操作。假设如果是一个很复杂的类,你又不能轻易去改的情况下,在某个部分要给它增加后续的操作。 * 你也许会想,那这样我直接继承然后调用不就完事了?干嘛整这么复杂?可你增加多个操作时,得一层一层的继承啊,当A继承B,B继承C,C继承D,输出ABCD,现在的需求是AD,中间就多了俩个类,如果更多的操作呢? * 而现在你只需将所有的装饰类继承装饰器类,将最高层的基类传入装饰类,就实现了"继承"的效果,而且是动态的。要用什么就装饰什么。 */
    最新回复(0)