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

PHP设计模式之装饰器模式实例详解

发布:smiling 来源: PHP粉丝网  添加日期:2021-09-03 10:45:20 浏览: 评论:0 

本文实例讲述了PHP设计模式之装饰器模式。分享给大家供大家参考,具体如下:

装饰器模式又叫装饰者模式。装饰模式是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。

角色:

组件对象的接口:可以给这些对象动态的添加职责

所有装饰器的父类:需要定义一个与组件接口一致的接口,并持有一个Component对象,该对象其实就是被装饰的对象。

具体的装饰器类:实现具体要向被装饰对象添加的功能,用来装饰具体的组件对象或者另外一个具体的装饰器对象。

具体代码:

  1. <?php 
  2. /** 
  3.  * Created by PhpStorm. 
  4.  * User: Jiang 
  5.  * Date: 2015/5/3 
  6.  * Time: 11:11 
  7.  */ 
  8. /**组件对象接口 
  9.  * Interface IComponent 
  10.  */ 
  11. interface IComponent 
  12. { 
  13.   function Display(); 
  14. } 
  15. /**待装饰对象 
  16.  * Class Person 
  17.  */ 
  18. class Person implements IComponent 
  19. { 
  20.   private $name; 
  21.   function __construct($name) 
  22.   { 
  23.     $this->name=$name; 
  24.   } 
  25.   function Display() 
  26.   { 
  27.     echo "装扮的:{$this->name}<br/>"; 
  28.   } 
  29. } 
  30. /**所有装饰器父类 
  31.  * Class Clothes 
  32.  */ 
  33. class Clothes implements IComponent 
  34. { 
  35.   protected $component; 
  36.   function Decorate(IComponent $component) 
  37.   { 
  38.     $this->component=$component; 
  39.   } 
  40.   function Display() 
  41.   { 
  42.     if(!emptyempty($this->component)) 
  43.     { 
  44.       $this->component->Display(); 
  45.     } 
  46.   } 
  47. } 
  48. //------------------------------具体装饰器---------------- 
  49. class PiXie extends Clothes 
  50. { 
  51.   function Display() 
  52.   { 
  53.     echo "皮鞋 "; 
  54.     parent::Display(); 
  55.   } 
  56. } 
  57. class QiuXie extends Clothes 
  58. { 
  59.   function Display() 
  60.   { 
  61.     echo "球鞋 "; 
  62.     parent::Display(); 
  63.   } 
  64. } 
  65. class Tshirt extends Clothes 
  66. { 
  67.   function Display() 
  68.   { 
  69.     echo "T恤 "; 
  70.     parent::Display(); 
  71.   } 
  72. } 
  73. class Waitao extends Clothes 
  74. { 
  75.   function Display() 
  76.   { 
  77.     echo "外套 "; 
  78.     parent::Display(); 
  79.   } 
  80. } 

调用客户端测试代码:

  1. header("Content-Type:text/html;charset=utf-8"); 
  2. //------------------------装饰器模式测试代码------------------ 
  3. require_once "./Decorator/Decorator.php"; 
  4. $Yaoming=new Person("姚明"); 
  5. $aTai=new Person("A泰斯特"); 
  6. $pixie=new PiXie(); 
  7. $waitao=new Waitao(); 
  8. $pixie->Decorate($Yaoming); 
  9. $waitao->Decorate($pixie); 
  10. $waitao->Display(); 
  11. echo "<hr/>"; 
  12. $qiuxie=new QiuXie(); 
  13. $tshirt=new Tshirt(); 
  14. $qiuxie->Decorate($aTai); 
  15. $tshirt->Decorate($qiuxie); 
  16. $tshirt->Display(); 

适用场景:

1. 需要动态的给一个对象添加功能,这些功能可以再动态的撤销。

2. 需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变的不现实。

3. 当不能采用生成子类的方法进行扩充时。一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长,另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类。

Tags: PHP设计模式

分享到: