裝飾器模式就是對一個已有的結構增長裝飾。裝飾模式是在沒必要改變原類文件和使用繼承的狀況下,動態地擴展一個對象的功能。它是經過建立一個包裝對象,也就是裝飾來包裹真實的對象。 php
基本說來, 若是想爲現有對象增長新功能而不想影響其餘對象, 就能夠使用裝飾器模式. 設計模式
<?php namespace Test; abstract class Component { abstract public function operation(); }
<?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(); }
<?php namespace Test; class ConcreteComponent extends Component { public function operation() { echo "hello world!!!!"; } }
<?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!!!"; } }
<?php namespace Test; class Client { /** * */ public static function main() { $decoratorA = new ConcreteDecoratorA(new ConcreteComponent()); $decoratorA->operation(); $decoratorB=new ConcreteDecoratorA($decoratorA); $decoratorB->operation(); } }
before!!!hello world!!!!after!!!before!!!before!!!hello world!!!!after!!!after!!!