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

yipeiwu_com5年前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 . '<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相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

PHP 网页过期时间的控制代码

当然,前提要先打开CDN中一个功能reload_into_ims on.这样用户发送过来no-cache也不怕了.因为这样会给给no-cache转成If-Modified-Since ....

php+js iframe实现上传头像界面无跳转

上传头像,界面无跳转的方式很多,我用的是加个iframe那种。下面直接上代码。 html: 复制代码 代码如下: //route 为后端接口 //upload/avatar 为上传的头像...

PHP使用memcache缓存技术提高响应速度的方法

本文实例讲述了PHP使用memcache缓存技术提高响应速度的方法。分享给大家供大家参考。具体分析如下: php虽然己经做到很好很快了,但是如果大数据量时还是会有些卡了,这里介绍一下PH...

使用php shell命令合并图片的代码

复制代码 代码如下: #!/usr/local/bin/php -q author:freemouse <?php // 下面是说明. print ("本程序用于合并2张 640x...

PHP实现上传多图即时显示与即时删除的方法

PHP实现上传多图即时显示与即时删除的方法

本文实例讲述了PHP实现上传多图即时显示与即时删除的方法。分享给大家供大家参考,具体如下: 就像这样的,每选择一个图片就会即时显示出来,附加到右边,也可以随意删除一个元素。 其实是,当...