温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在php中应用装饰者模式

发布时间:2021-06-07 17:28:12 来源:亿速云 阅读:106 作者:Leah 栏目:开发技术

这期内容当中小编将会给大家带来有关怎么在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中应用装饰者模式了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI