您的位置:首页 >PHP装饰器模式面试题解析
发布于2026-03-17 阅读(0)
扫一扫,手机访问
PHP中无原生装饰器语法,但可通过实现统一接口、组合被装饰对象来模拟装饰器模式,支持链式调用与多层增强,核心是动态扩展行为而不修改原类。

PHP 中没有原生装饰器语法(如 Python 的 @decorator),但可以通过面向对象方式模拟装饰器模式,核心是「动态扩展对象行为,不修改原有类」。面试中常考的是手写一个可链式调用、支持多层增强的装饰器结构。
装饰器模式属于结构型设计模式,关键在于:装饰器类和被装饰类实现同一接口,装饰器内部持有被装饰对象的引用,并在方法调用前后插入逻辑。
Processor),让原始类和所有装饰器都实现它$this->wrapped->handle() 委托调用以下是一个简洁可用的面试级实现,支持多层包装:
// 接口
interface Processor {
public function handle(string $data): string;
}
// 原始处理器
class TextProcessor implements Processor {
public function handle(string $data): string {
return trim($data);
}
}
// 日志装饰器
class LoggingDecorator implements Processor {
private Processor $wrapped;
public function __construct(Processor $wrapped) {
$this->wrapped = $wrapped;
}
public function handle(string $data): string {
echo "[LOG] Processing: " . $data . "\n";
return $this->wrapped->handle($data);
}
}
// 大写装饰器
class UppercaseDecorator implements Processor {
private Processor $wrapped;
public function __construct(Processor $wrapped) {
$this->wrapped = $wrapped;
}
public function handle(string $data): string {
$result = $this->wrapped->handle($data);
return strtoupper($result);
}
}
// 使用示例
$processor = new TextProcessor();
$processor = new LoggingDecorator($processor);
$processor = new UppercaseDecorator($processor);
echo $processor->handle(" hello world "); // 输出:[LOG] Processing: hello world \nHELLO WORLD
面试官常围绕灵活性、性能、边界场景提问:
add()/remove() 方法,handle() 中遍历执行$next()),装饰器更通用写错容易暴露基础薄弱:
$wrapped->handle()(应延迟到业务方法中)handle() 方法,保持接口统一上一篇:波点音乐一起听设置方法详解
下一篇:搜狗浏览器设置启动页方法
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9