本文實例講述了php裝飾者模式簡單應用。分享給大家供大家參考,具體如下:
裝飾模式指的是在不必改變原類文件和使用繼承的情況下,動態(tài)地擴展一個對象的功能。它是通過創(chuàng)建一個包裝對象,也就是裝飾來包裹真實的對象。
示例:
A、B、C編輯同一篇文章。
class Article{ protected $content; public function __construct($info){ $this->content = $info; } } class editor_A extends Article{ public function __construct(Article $obj){ $this->content = $obj->content . 'br/>' . '編輯A新寫的內容'; } public function decorator(){ return $this->content; } } class editor_B extends Article{ public function __construct(Article $obj){ $this->content = $obj->content . 'br/>' . '編輯B新寫的內容'; } public function decorator(){ return $this->content; } } class editor_C extends Article{ public function __construct(Article $obj){ $this->content = $obj->content . 'br/>' . '編輯C新寫的內容'; } public function decorator(){ return $this->content; } } $artCls = new Article('你好'); //編輯A先秀修改,然后編輯B修改,然后編輯C修改 $a = new editor_A($artCls); $b = new editor_B($a); $c = new editor_C($b); echo $c->decorator(); //編輯B先秀修改,然后編輯A修改 $b = new editor_B($artCls); $a = new editor_A($b); echo $a->decorator(); //重點是傳遞參數的地方,使用Article $obj傳遞上一個操作的對象, //來實現對同一個對象進行連續(xù)操作
運行結果:
你好
編輯A新寫的內容
編輯B新寫的內容
編輯C新寫的內容你好
編輯B新寫的內容
編輯A新寫的內容
更多關于PHP相關內容感興趣的讀者可查看本站專題:《php面向對象程序設計入門教程》、《PHP數組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。