首页 > 开发 > PHP > 正文

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

2024-05-04 23:34:59
字体:大 中 小
来源:转载
供稿:网友

这篇文章主要介绍了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(); 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表