装饰器模式的外在形式是一个简单的类嵌套在一个类中的递归调用生成子类Flexible*///ComponentinterfaceInterfaceComponent{publicfunctionoperation();}//具体组件实现类ConcreteComponentimplementsComponent{publicfunctionoperation(){echo"concrete_componentshandle\n";}}//装饰器类classDecoratorimplementsComponent{protected$component;publicfunction__construct(Component$component){$this->component=$component;}publicfunctionoperation(){$this->component->operation();}}//装饰器AclassDecoratorAextendsDecorator{publicfunction__construct(Component$comp){parent::__construct($comp);}publicfunctionoperation(){parent::operation();echo"这是decorator_A\n";}}//装饰器组件BclassDecoratorBextendsDecorator{publicfunction__construct(Component$comp){parent::__construct($comp);}公共函数操作(){父母::操作();echo"这是decorator_B\n";}}try{//不断的装饰//核心在于每个类的构造函数的组件挂载(即装饰)$component=newConcreteComponent();$a=newDecoratorA($component);$b=新装饰器B($a);//统一输出$b->operation();}catch(Exception$e){echo$e->getMessage();}
