php裝飾者模式簡單應用案例分析
本文實例講述了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();
//重點是傳遞參數(shù)的地方,使用Article $obj傳遞上一個操作的對象,
//來實現(xiàn)對同一個對象進行連續(xù)操作
運行結果:
你好
編輯A新寫的內容
編輯B新寫的內容
編輯C新寫的內容你好
編輯B新寫的內容
編輯A新寫的內容
更多關于PHP相關內容感興趣的讀者可查看本站專題:《php面向對象程序設計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
相關文章
PHP抽象工廠模式Abstract Factory Pattern優(yōu)點與實現(xiàn)方式
這篇文章主要介紹了PHP抽象工廠模式Abstract Factory Pattern優(yōu)點與實現(xiàn)方式,抽象工廠模式是一種創(chuàng)建型模式,它提供了一種創(chuàng)建一系列相關或相互依賴對象的最佳方式2023-03-03
PHP函數(shù)shuffle()取數(shù)組若干個隨機元素的方法分析
這篇文章主要介紹了PHP函數(shù)shuffle()取數(shù)組若干個隨機元素的方法,結合實例形式詳細分析了shuffle函數(shù)的功能,定義,使用方法與相關注意事項,需要的朋友可以參考下2016-04-04

