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来对对象进行包装的。这样,每个装饰对象的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链接中。
时间: 2024-10-13 10:52:34