欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

學(xué)習(xí)php設(shè)計(jì)模式 php實(shí)現(xiàn)裝飾器模式(decorator)

 更新時(shí)間:2015年12月07日 11:30:13   作者:胖胖  
這篇文章主要介紹了php設(shè)計(jì)模式中的裝飾模式,使用php實(shí)現(xiàn)裝飾模式,感興趣的小伙伴們可以參考一下

動(dòng)態(tài)的給一個(gè)對(duì)象添加一些額外的職責(zé)。就增加功能來(lái)說(shuō),Decorator模式相比生成子類更為靈活【GOF95】
裝飾模式是以對(duì)客戶透明的方式動(dòng)態(tài)地給一個(gè)對(duì)象附加上更多的職責(zé)。這也就是說(shuō),客戶端并不會(huì)覺(jué)得對(duì)象在裝飾前和裝飾后有什么不同。裝飾模式可以在不使用創(chuàng)造更多子類的情況下,將對(duì)象的功能加以擴(kuò)展。
一、裝飾模式結(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();
?>

以上就是使用php實(shí)現(xiàn)裝飾模式的代碼,還有一些關(guān)于裝飾模式的概念區(qū)分,希望對(duì)大家的學(xué)習(xí)有所幫助。

相關(guān)文章

最新評(píng)論