码迷,mamicode.com
首页 > Web开发 > 详细

大话设计模式第六章---装饰模式PHP实现

时间:2015-08-29 18:29:32      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

 1 <?php
 2 abstract class Component {
 3     abstract public function operation();
 4 }
 5 
 6 class Concrete_component extends Component {
 7     public function operation() {
 8         echo "具体对象的操作<br/>";
 9     }
10 }
11 
12 abstract class Decorator extends Component {
13     protected $component;
14 
15     public function set_component(Component $component) {
16         $this->component = $component;
17     }
18 
19     public function operation() {
20         if ($this->component != null) {
21             $this->component->operation();
22         }
23     }
24 }
25 
26 class Concrete_decorator_A extends Decorator {
27     private $added_state;    //鏈被鐗规湁鐨勫姛鑳斤紝浠ュ尯鍒玞oncrete_decorator_A
28 
29     public function operation() {
30         parent::operation();
31         $added_state = ‘New State‘;
32         echo "具体装饰对象A的操作<br/>";
33     }
34 }
35 
36 class Concrete_decorator_B extends Decorator {
37     public function operation() {
38         parent::operation();
39         $this->added_behavior();
40         echo "具体装饰对象B的操作<br/>";
41     }
42 
43     private function added_behavior(){
44     }
45 }
46 
47 
48 
49 //涓嬮潰鏄鎴风浠g爜
50 $c  = new Concrete_component();
51 $d1 = new Concrete_decorator_A();
52 $d2 = new Concrete_decorator_B();
53 
54 $d1->set_component($c);
55 $d2->set_component($d1);
56 $d2->operation();

技术分享

 

装饰模式:

  动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更灵活。

  装饰模式是利用set_component来对对象进行包装的。这样,每个装饰对象的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链接中。

大话设计模式第六章---装饰模式PHP实现

标签:

原文地址:http://www.cnblogs.com/wy0314/p/4769439.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!