服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - PHP教程 - php装饰者模式简单应用案例分析

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

2021-09-13 16:57学知无涯 PHP教程

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

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

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

示例:

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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程序设计有所帮助。

原文链接:https://www.cnblogs.com/gyfluck/p/9681874.html

延伸 · 阅读

精彩推荐