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 PrefixDecorator extends Decorator {
public function operation(): string {
return "Prefix_" . parent::operation();
}
}
class SuffixDecorator extends Decorator {
public function operation(): string {
return parent::operation() . "_Suffix";
}
}
使用示例
通过嵌套装饰器动态组合功能:
$component = new ConcreteComponent();
$decorated = new PrefixDecorator(new SuffixDecorator($component));
echo $decorated->operation(); // 输出: Prefix_ConcreteComponent_Suffix
实际应用场景
- 日志记录:在不修改业务类的情况下添加日志功能。
- 权限校验:动态为接口调用添加权限检查层。
- 数据格式化:对原始数据逐步进行加密、压缩等处理。
优势与注意事项
- 优势:符合开闭原则,支持动态组合功能。
- 注意事项:避免过度嵌套导致代码复杂度上升,装饰顺序可能影响结果。






