Chinaunix首页 | 论坛 | 博客
  • 博客访问: 70025
  • 博文数量: 18
  • 博客积分: 492
  • 博客等级: 下士
  • 技术积分: 200
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-24 20:27
文章分类
文章存档

2011年(18)

分类: 系统运维

2011-04-11 23:14:57

  1. <?php
  2. /**
  3. * 装饰者模式
  4. */

  5. /**
  6.  * 冰激凌抽象类
  7.  */
  8. abstract class ICE
  9. {
  10.     public abstract function getDescription();
  11.     public abstract function cost();
  12. }

  13. /**
  14.  * 牛奶冰激凌,售价17RMB
  15.  */
  16. class MilkIce extends ICE
  17. {
  18.     public $description = '纯牛奶制作的冰激凌';

  19.     public function getDescription()
  20.     {
  21.         return $this->description;
  22.     }

  23.     public function cost()
  24.     {
  25.         return 17;
  26.     }
  27. }

  28. /**
  29.  * 沙冰冰激凌,售价10RMB
  30.  */
  31. class SlushIce extends ICE
  32. {
  33.     public $description = '冰块制作的冰激凌';

  34.     public function getDescription()
  35.     {
  36.         return $this->description;
  37.     }

  38.     public function cost()
  39.     {
  40.         return 10;
  41.     }
  42. }

  43. /**
  44.  * 冰激凌调料抽象类
  45.  */
  46. abstract class CondimentIce extends ICE
  47. {
  48.     //public abstract function getDescription();
  49.     //public abstract function cost();
  50. }

  51. /**
  52.  * 加香菜口味,附加5RMB
  53.  */
  54. class Herb extends CondimentIce
  55. {
  56.     public $ice;
  57.     public $description;

  58.     public function __construct($ice)
  59.     {
  60.         $this->ice = $ice;
  61.         $this->description = '法国香草';
  62.     }

  63.     public function getDescription()
  64.     {
  65.         return $this->ice->getDescription() . ',' . $this->description;
  66.     }

  67.     public function cost()
  68.     {
  69.         return $this->ice->cost() + 5;
  70.     }
  71. }

  72. /**
  73.  * 加草莓口味,附加8RMB
  74.  */
  75. class Berries extends CondimentIce
  76. {
  77.     public $ice;
  78.     public $description;

  79.     public function __construct($ice)
  80.     {
  81.         $this->ice = $ice;
  82.         $this->description = '野草莓';
  83.     }

  84.     public function getDescription()
  85.     {
  86.         return $this->ice->getDescription() . ',' . $this->description;
  87.     }

  88.     public function cost()
  89.     {
  90.         return $this->ice->cost() + 8;
  91.     }
  92. }


  93. // example
  94. // 购买一个奶油香草冰激凌
  95. $ice_object = new MilkIce();
  96. $ice_object = new Herb($ice_object);
  97. echo $ice_object->cost();
  98. echo $ice_object->getDescription();

  99. // 购买一个沙冰+香草+草莓
  100. $ice2 = new SlushIce();
  101. $ice2 = new Herb($ice2);
  102. $ice2 = new Berries($ice2);
  103. echo $ice2->cost();
  104. echo $ice2->getDescription();



是不是有些像递归调用
阅读(1244) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~