php裝飾者模式簡單應(yīng)用案例分析
本文實例講述了php裝飾者模式簡單應(yīng)用。分享給大家供大家參考,具體如下:
裝飾模式指的是在不必改變原類文件和使用繼承的情況下,動態(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新寫的內(nèi)容';
}
public function decorator(){
return $this->content;
}
}
class editor_B extends Article{
public function __construct(Article $obj){
$this->content = $obj->content . '<br/>' . '編輯B新寫的內(nèi)容';
}
public function decorator(){
return $this->content;
}
}
class editor_C extends Article{
public function __construct(Article $obj){
$this->content = $obj->content . '<br/>' . '編輯C新寫的內(nèi)容';
}
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ù)操作
運行結(jié)果:
你好
編輯A新寫的內(nèi)容
編輯B新寫的內(nèi)容
編輯C新寫的內(nèi)容你好
編輯B新寫的內(nèi)容
編輯A新寫的內(nèi)容
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
- PHP設(shè)計模式之裝飾者模式代碼實例
- PHP設(shè)計模式之裝飾者模式
- php設(shè)計模式 Decorator(裝飾模式)
- 學(xué)習(xí)php設(shè)計模式 php實現(xiàn)裝飾器模式(decorator)
- PHP面向?qū)ο蟪绦蛟O(shè)計組合模式與裝飾模式詳解
- PHP設(shè)計模式之裝飾器模式定義與用法詳解
- php適配器模式簡單應(yīng)用示例
- php橋接模式應(yīng)用案例分析
- php 策略模式原理與應(yīng)用深入理解
- php設(shè)計模式之工廠模式用法經(jīng)典實例分析
- php設(shè)計模式之觀察者模式定義與用法經(jīng)典示例
- php設(shè)計模式之職責(zé)鏈模式定義與用法經(jīng)典示例
相關(guān)文章
PHP抽象工廠模式Abstract Factory Pattern優(yōu)點與實現(xiàn)方式
這篇文章主要介紹了PHP抽象工廠模式Abstract Factory Pattern優(yōu)點與實現(xiàn)方式,抽象工廠模式是一種創(chuàng)建型模式,它提供了一種創(chuàng)建一系列相關(guān)或相互依賴對象的最佳方式2023-03-03
PHP函數(shù)shuffle()取數(shù)組若干個隨機元素的方法分析
這篇文章主要介紹了PHP函數(shù)shuffle()取數(shù)組若干個隨機元素的方法,結(jié)合實例形式詳細(xì)分析了shuffle函數(shù)的功能,定義,使用方法與相關(guān)注意事項,需要的朋友可以參考下2016-04-04

