php装饰者模式简单应用案例分析

2022-04-15 0 294

本文实例讲述了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新写的内容

更多关于PHP相关内容感兴趣的读者可查看本站专题

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 PHP编程 php装饰者模式简单应用案例分析 https://www.niceym.com/13502.html