当前位置:首页 > PHP教程 > php应用 > 列表

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

发布:smiling 来源: PHP粉丝网  添加日期:2022-01-16 17:16:21 浏览: 评论:0 

这篇文章主要介绍了php装饰者模式简单应用,结合具体实例形式分析了php装饰者模式的原理及文章编辑相关应用操作技巧,需要的朋友可以参考下。

本文实例讲述了php装饰者模式简单应用,分享给大家供大家参考,具体如下:

装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能,它是通过创建一个包装对象,也就是装饰来包裹真实的对象。

示例:

A、B、C编辑同一篇文章。

  1. class Article{ 
  2.   protected $content; 
  3.   public function __construct($info){ 
  4.     $this->content = $info; 
  5.   } 
  6. } 
  7. class editor_A extends Article{ 
  8.   public function __construct(Article $obj){ 
  9.     $this->content = $obj->content . '<br/>' . '编辑A新写的内容'; 
  10.   } 
  11.   public function decorator(){ 
  12.     return $this->content; 
  13.   } 
  14. } 
  15. class editor_B extends Article{ 
  16.   public function __construct(Article $obj){ 
  17.     $this->content = $obj->content . '<br/>' . '编辑B新写的内容'; 
  18.   } 
  19.   public function decorator(){ 
  20.     return $this->content; 
  21.   } 
  22. } 
  23. class editor_C extends Article{ 
  24.   public function __construct(Article $obj){ 
  25.     $this->content = $obj->content . '<br/>' . '编辑C新写的内容'; 
  26.   } 
  27.   public function decorator(){ 
  28.     return $this->content; 
  29.   } 
  30. } 
  31. $artCls = new Article('你好'); 
  32. //编辑A先秀修改,然后编辑B修改,然后编辑C修改 
  33. $a = new editor_A($artCls); 
  34. $b = new editor_B($a); 
  35. $c = new editor_C($b); 
  36. echo $c->decorator(); 
  37. //编辑B先秀修改,然后编辑A修改 
  38. $b = new editor_B($artCls); 
  39. $a = new editor_A($b); 
  40. echo $a->decorator(); 

重点是传递参数的地方,使用Article $obj传递上一个操作的对象,来实现对同一个对象进行连续操作

运行结果:

你好

编辑A新写的内容

编辑B新写的内容

编辑C新写的内容你好

编辑B新写的内容

编辑A新写的内容

Tags: php装饰者模式

分享到: