裝飾器設計模式
什麼是裝飾器模式
裝飾器模式就是對一個已有的結構增長裝飾。裝飾模式是在沒必要改變原類文件和使用繼承的狀況下,動態地擴展一個對象的功能。它是經過建立一個包裝對象,也就是裝飾來包裹真實的對象。php
什麼時候使用裝飾器
基本說來, 若是想爲現有對象增長新功能而不想影響其餘對象, 就能夠使用裝飾器模式.設計模式
裝飾器類圖
裝飾器的組成
- Component接口:定義一個對象接口,以規範準備接受附加責任的對象。
- Decorator接口:裝飾器接口
- ConcreteComponent :具體組件角色,即將要被裝飾增長功能的類
- ConcreteDecorator :具體裝飾器,向組件添加職責
代碼
Component接口
<?php namespace Test; abstract class Component { abstract public function operation(); }
Decorator
<?php namespace Test; abstract class Decorator extends Component { protected $component; public function __construct(Component $component) { $this->component = $component; } public function operation() { $this->component->operation(); } abstract public function before(); abstract public function after(); }
ConcreteComponent
<?php namespace Test; class ConcreteComponent extends Component { public function operation() { echo "hello world!!!!"; } }
ConcreteDecoratorA 添加了before和after方法,即在原有操做的基礎上以前和以後又添加了職責
<?php namespace Test; class ConcreteDecoratorA extends Decorator { public function __construct(Component $component) { parent::__construct($component); } public function operation() { $this->before(); parent::operation(); $this->after(); } public function before() { // TODO: Implement before() method. echo "before!!!"; } public function after() { // TODO: Implement after() method. echo "after!!!"; } }
CLient主要用來實例化裝飾器
<?php namespace Test; class Client { /** * */ public static function main() { $decoratorA = new ConcreteDecoratorA(new ConcreteComponent()); $decoratorA->operation(); $decoratorB=new ConcreteDecoratorA($decoratorA); $decoratorB->operation(); } }
調用Clien main()方法結果
before!!!hello world!!!!after!!!before!!!before!!!hello world!!!!after!!!after!!!