php实现装饰
装饰器模式简介
装饰器模式是一种结构型设计模式,允许动态地为对象添加功能,而无需修改其原始类。通过将对象包装在装饰器类中,可以在运行时扩展行为,符合开闭原则(对扩展开放,对修改封闭)。
PHP实现装饰器模式的核心步骤
定义组件接口
创建一个接口或抽象类,声明被装饰对象和装饰器的共同方法。

interface Component {
public function operation(): string;
}
实现具体组件
定义基础组件类,实现核心功能。
class ConcreteComponent implements Component {
public function operation(): string {
return "ConcreteComponent";
}
}
创建装饰器基类
装饰器基类实现相同的接口,并持有组件对象的引用。

class Decorator implements Component {
protected $component;
public function __construct(Component $component) {
$this->component = $component;
}
public function operation(): string {
return $this->component->operation();
}
}
实现具体装饰器
扩展装饰器基类,添加新功能。
class ConcreteDecoratorA extends Decorator {
public function operation(): string {
return "DecoratorA(" . parent::operation() . ")";
}
}
class ConcreteDecoratorB extends Decorator {
public function operation(): string {
return "DecoratorB(" . parent::operation() . ")";
}
}
使用示例
动态组合装饰器和组件对象:
$simple = new ConcreteComponent();
echo $simple->operation(); // 输出: ConcreteComponent
$decoratorA = new ConcreteDecoratorA($simple);
echo $decoratorA->operation(); // 输出: DecoratorA(ConcreteComponent)
$decoratorB = new ConcreteDecoratorB($decoratorA);
echo $decoratorB->operation(); // 输出: DecoratorB(DecoratorA(ConcreteComponent))
实际应用场景
- 日志记录:在不修改业务逻辑类的情况下,添加日志记录功能。
- 缓存层:通过装饰器为数据访问对象动态添加缓存。
- 权限校验:在核心功能外包装权限检查逻辑。
通过装饰器模式,可以灵活地组合功能,避免类爆炸问题,同时保持代码的可维护性。






