PHP装饰者模式动态扩展对象功能案例分析
本实例详细解析了PHP中装饰者模式的实际应用方法,旨在为读者提供可参考的代码实践与思路。
所谓装饰模式,其核心在于不需要改动原有类的源代码,也不依赖继承机制,即可实现对对象功能的动态增强。具体做法是构建一个包装类(即装饰器),将真实对象包裹其中,从而在运行时扩展其行为。
以下通过一个具体的场景来说明该模式的使用方式。
假设存在A、B、C三位编辑人员,他们需要对同一篇文章内容进行连续的编辑操作。
class Article{
protected $content;
public function __construct($info){
$this->content = $info;
}
}
class editor_A extends Article{
public function __construct(Article $obj){
$this->content = $obj->content . '
' . '编辑A新写的内容';
}
public function decorator(){
return $this->content;
}
}
class editor_B extends Article{
public function __construct(Article $obj){
$this->content = $obj->content . '
' . '编辑B新写的内容';
}
public function decorator(){
return $this->content;
}
}
class editor_C extends Article{
public function __construct(Article $obj){
$this->content = $obj->content . '
' . '编辑C新写的内容';
}
public function decorator(){
return $this->content;
}
}
$artCls = new Article('你好');
//编辑A先秀修改,然后编辑B修改,然后编辑C修改
$a = new editor_A($artCls);
$b = new editor_B($a);
$c = new editor_C($b);
echo $c->decorator();
//编辑B先秀修改,然后编辑A修改
$b = new editor_B($artCls);
$a = new editor_A($b);
echo $a->decorator();
//重点是传递参数的地方,使用Article $obj传递上一个操作的对象,
//来实现对同一个对象进行连续操作
程序执行后的输出结果如下所示。
你好 编辑A新写的内容 编辑B新写的内容 编辑C新写的内容你好 编辑B新写的内容 编辑A新写的内容
期望上述关于PHP程序设计中的装饰者模式案例,能对广大开发者有所帮助。