装饰器模式
文章目录
装饰器模式
外在形式是类套类
简单类递归调用
<?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();
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论