您好,登錄后才能下訂單哦!
怎么在php中實(shí)現(xiàn)一個(gè)裝飾器模式?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
一、裝飾模式結(jié)構(gòu)圖
二、裝飾模式中主要角色
抽象構(gòu)件(Component)角色:定義一個(gè)對(duì)象接口,以規(guī)范準(zhǔn)備接收附加職責(zé)的對(duì)象,從而可以給這些對(duì)象動(dòng)態(tài)地添加職責(zé)。
具體構(gòu)件(Concrete Component)角色:定義一個(gè)將要接收附加職責(zé)的類。
裝飾(Decorator)角色:持有一個(gè)指向Component對(duì)象的指針,并定義一個(gè)與Component接口一致的接口。
具體裝飾(Concrete Decorator)角色:負(fù)責(zé)給構(gòu)件對(duì)象增加附加的職責(zé)。
三、裝飾模式的優(yōu)缺點(diǎn)
裝飾模式的優(yōu)點(diǎn):
1、比靜態(tài)繼承更靈活;
2、避免在層次結(jié)構(gòu)高層的類有太多的特征
裝飾模式的缺點(diǎn):
1、使用裝飾模式會(huì)產(chǎn)生比使用繼承關(guān)系更多的對(duì)象。并且這些對(duì)象看上去都很想像,從而使得查錯(cuò)變得困難。
四、裝飾模式適用場(chǎng)景
1、在不影響其他對(duì)象的情況下,以動(dòng)態(tài)、透明的方式給單個(gè)對(duì)象添加職責(zé)。
2、處理那些可以撤消的職責(zé),即需要?jiǎng)討B(tài)的給一個(gè)對(duì)象添加功能并且這些功能是可以動(dòng)態(tài)的撤消的。
3、當(dāng)不能彩生成子類的方法進(jìn)行擴(kuò)充時(shí)。一種情況是,可能有大量獨(dú)立的擴(kuò)展,為支持每一種組合將產(chǎn)生大量的子類,使得子類數(shù)目呈爆炸性增長(zhǎng)。另一種情況可能是因?yàn)轭惗x被隱藏,或類定義不能用于生成子類。
五、裝飾模式PHP示例
<?php /** * 抽象構(gòu)件角色 */ interface Component { /** * 示例方法 */ public function operation(); } /** * 裝飾角色 */ abstract class Decorator implements Component{ protected $_component; public function __construct(Component $component) { $this->_component = $component; } public function operation() { $this->_component->operation(); } } /** * 具體裝飾類A */ class ConcreteDecoratorA extends Decorator { public function __construct(Component $component) { parent::__construct($component); } public function operation() { parent::operation(); // 調(diào)用裝飾類的操作 $this->addedOperationA(); // 新增加的操作 } /** * 新增加的操作A,即裝飾上的功能 */ public function addedOperationA() { echo 'Add Operation A <br />'; } } /** * 具體裝飾類B */ class ConcreteDecoratorB extends Decorator { public function __construct(Component $component) { parent::__construct($component); } public function operation() { parent::operation(); $this->addedOperationB(); } /** * 新增加的操作B,即裝飾上的功能 */ public function addedOperationB() { echo 'Add Operation B <br />'; } } /** * 具體構(gòu)件 */ class ConcreteComponent implements Component{ public function operation() { echo 'Concrete Component operation <br />'; } } /** * 客戶端 */ class Client { /** * Main program. */ public static function main() { $component = new ConcreteComponent(); $decoratorA = new ConcreteDecoratorA($component); $decoratorB = new ConcreteDecoratorB($decoratorA); $decoratorA->operation(); $decoratorB->operation(); } } Client::main(); ?>
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。