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 "ConcreteDecoratorA(" . parent::operation() . ")";
}
}
class ConcreteDecoratorB extends Decorator {
public function operation(): string {
return "ConcreteDecoratorB(" . parent::operation() . ")";
}
}
使用示例
客户端代码可以这样组合装饰器和组件
$simple = new ConcreteComponent();
echo $simple->operation(); // 输出: ConcreteComponent
$decorator1 = new ConcreteDecoratorA($simple);
$decorator2 = new ConcreteDecoratorB($decorator1);
echo $decorator2->operation(); // 输出: ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent))
实际应用场景
日志记录装饰器示例
class LoggerDecorator implements Component {
private $component;
public function __construct(Component $component) {
$this->component = $component;
}
public function operation(): string {
$result = $this->component->operation();
// 添加日志记录功能
file_put_contents('log.txt', date('Y-m-d H:i:s').': '.$result.PHP_EOL, FILE_APPEND);
return $result;
}
}
缓存装饰器示例
class CacheDecorator implements Component {
private $component;
private $cache = [];
public function __construct(Component $component) {
$this->component = $component;
}
public function operation(): string {
$key = get_class($this->component);
if (!isset($this->cache[$key])) {
$this->cache[$key] = $this->component->operation();
}
return $this->cache[$key];
}
}
装饰器模式优势
- 比继承更灵活,可以在运行时添加或移除功能
- 避免子类爆炸问题
- 符合开闭原则,对扩展开放对修改关闭
- 可以嵌套多个装饰器实现功能组合
注意事项
- 装饰器必须与组件接口一致
- 大量小对象可能增加系统复杂度
- 调试装饰器包装的对象可能比较困难
通过合理使用装饰器模式,可以动态地为PHP对象添加各种功能,保持代码的灵活性和可维护性。






