装饰器模式就是对一个已有的结构增长装饰。装饰模式是在没必要改变原类文件和使用继承的状况下,动态地扩展一个对象的功能。它是经过建立一个包装对象,也就是装饰来包裹真实的对象。 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!!!