当前位置:首页 > PHP教程 > php应用 > 列表

PHP设计模式之装饰者模式代码实例

发布:smiling 来源: PHP粉丝网  添加日期:2021-05-26 15:04:21 浏览: 评论:0 

这篇文章主要介绍了PHP设计模式之装饰者模式代码实例,装饰者模式就是不修改原类代码和继承的情况下动态扩展类的功能,本文就给出了代码实例,需要的朋友可以参考下

定义:装饰者模式就是不修改原类代码和继承的情况下动态扩展类的功能。传统的编程模式都是子类继承父类实现方法重载,使用装饰器模式,只需添加一个新的装饰器对象,更加灵活,避免类数量和层次过多。

角色:

Component(被装饰对象基类)

ConcreteComponent(具体被装饰对象)

Decorator(装饰者基类)

ContreteDecorator(具体的装饰者类)

示例代码:

  1. //被装饰者基类 
  2. interface Component 
  3. { 
  4.   public function operation(); 
  5. } 
  6.    
  7. //装饰者基类 
  8. abstract class Decorator implements Component 
  9. { 
  10.   protected $component; 
  11.    
  12.   public function __construct(Component $component) 
  13.   { 
  14.     $this->component = $component; 
  15.   } 
  16.    
  17.   public function operation() 
  18.   { 
  19.     $this->component->operation(); 
  20.   } 
  21. } 
  22.    
  23. //具体装饰者类 
  24. class ConcreteComponent implements Component 
  25. { 
  26.   public function operation() 
  27.   { 
  28.     echo 'do operation'.PHP_EOL; 
  29.   } 
  30. } 
  31.    
  32. //具体装饰类A 
  33. class ConcreteDecoratorA extends Decorator { 
  34.   public function __construct(Component $component) { 
  35.     parent::__construct($component); 
  36.    
  37.   } 
  38.    
  39.   public function operation() { 
  40.     parent::operation(); 
  41.     $this->addedOperationA();  // 新增加的操作 
  42.   } 
  43.    
  44.   public function addedOperationA() { 
  45.     echo 'Add Operation A '.PHP_EOL; 
  46.   } 
  47. } 
  48.    
  49. //具体装饰类B 
  50. class ConcreteDecoratorB extends Decorator { 
  51.   public function __construct(Component $component) { 
  52.     parent::__construct($component); 
  53.    
  54.   } 
  55.    
  56.   public function operation() { 
  57.     parent::operation(); 
  58.     $this->addedOperationB(); 
  59.   } 
  60.    
  61.   public function addedOperationB() { 
  62.     echo 'Add Operation B '.PHP_EOL; 
  63.   } 
  64. } 
  65.    
  66.    
  67. class Client { 
  68.    
  69.   public static function main() { 
  70.     /* 
  71.     do operation 
  72.     Add Operation A 
  73.     */ 
  74.     $decoratorA = new ConcreteDecoratorA(new ConcreteComponent()); 
  75.     $decoratorA->operation(); 
  76.    
  77.    
  78.     /* 
  79.     do operation 
  80.     Add Operation A  
  81.     Add Operation B  
  82.     */ 
  83.     $decoratorB = new ConcreteDecoratorB($decoratorA); 
  84.     $decoratorB->operation(); 
  85.   } 
  86.    
  87. } 
  88.    
  89. Client::main();

Tags: PHP设计模式 PHP装饰者模式

分享到: