標籤:blog http io 使用 檔案 div on log cti
<?php /* * 裝飾模式:在不必改變原類檔案和使用繼承的情況下,動態地擴充一個對象的功能。它是通過建立一個封裝對象,也就是裝飾來包裹真實的對象。 * * 角色 * 抽象構件(Component)角色:定義一個對象介面,以規範準備接收附加職責的對象,從而可以給這些對象動態地添加職責。 * 具體構件(Concrete Component)角色:定義一個將要接收附加職責的類。 * 裝飾(Decorator)角色:持有一個指向Component對象的指標,並定義一個與Component介面一致的介面。 * 具體裝飾(Concrete Decorator)角色:負責給構件對象增加附加的職責。 *///1抽象構件角色abstract class drink{abstract function showprice();}//具體構件角色class coffee extends drink{public $name = ‘咖啡‘;public $price = ‘10‘;public function showprice(){echo $this->name.‘ ‘;echo $this->price.‘元‘;}}//產生對象。$coffee = new coffee();//$coffee->showprice();//上面我已經產生了一個對象,現在已經線上上運行//但是我想動態為coffee對象添加功能,而不改變原有的類和繼承關係,怎麼辦?//裝飾模式//裝飾角色class decretor extends drink{public $drink;public function __construct(drink $drink){//封裝了對象哦$this->drink = $drink;}public function showprice(){//實現對象原有功能,$this->drink->showprice();$this->add();//新增功能}public function add(){}}//具體裝飾角色class suger extends decretor{public $price = 1.5;public $name = ‘加糖‘;public function add(){echo $this->name.‘ ‘.$this->price;echo ‘ 一共‘.($this->drink->price+$this->price).‘元‘;}}$suger = new suger($coffee);$suger->showprice();?>
UML類圖如下:
php實現設計模式之 裝飾模式