本文实例讲述了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 . '<br/>' . '编辑a新写的内容';
  }
  public function decorator(){
    return $this->content;
  }
}
class editor_b extends article{
  public function __construct(article $obj){
    $this->content = $obj->content . '<br/>' . '编辑b新写的内容';
  }
  public function decorator(){
    return $this->content;
  }
}
class editor_c extends article{
  public function __construct(article $obj){
    $this->content = $obj->content . '<br/>' . '编辑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新写的内容