装饰器模式
外在形式是类套类
简单类递归调用
<?php
/**
* 装饰器模式: 动态的给一个对象添加额外的职责
* 就增加功能来说,装饰器模式比生成子类更为灵活
*/
// 组件接口
Interface Component
{
public function operation();
}
// 具体组件实现
class ConcreteComponent implements Component
{
public function operation()
{
echo "concrete_components handle\n";
}
}
// 装饰器类
class Decorator implements Component
{
protected $component;
public function __construct(Component $component)
{
$this->component = $component;
}
public function operation()
{
$this->component->operation();
}
}
// 装饰器A
class DecoratorA extends Decorator
{
public function __construct(Component $comp)
{
parent::__construct($comp);
}
public function operation()
{
parent::operation();
echo "it is decorator_A\n";
}
}
// 装饰器B
class DecoratorB extends Decorator
{
public function __construct(Component $comp)
{
parent::__construct($comp);
}
public function operation()
{
parent::operation();
echo "it is decorator_B\n";
}
}
try {
// 不断装饰
// 核心在于每个类的构造方法的组件挂载(即装饰)
$component = new ConcreteComponent();
$a = new DecoratorA($component);
$b = new DecoratorB($a);
// 统一输出
$b->operation();
} catch (Exception $e) {
echo $e->getMessage();
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。