裝飾器模式,顧名思義,就是對已經存在的某些類進行裝飾,以此來擴展一些功能。其結構圖以下: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修飾後的具體實現類」
何時使用?:通常的,咱們爲了擴展一個類常常使用繼承方式實現,因爲繼承爲類引入靜態特徵,而且隨着擴展功能的增多,子類會很膨脹。在不想增長不少子類的狀況下擴展類可使用這種設計模式設計模式