设计模式 装饰模式

WechatIMG31.jpeg

介绍

装饰模式是一种结构型设计模式,它允许动态地向对象添加新的行为,而不需要修改原有的代码。装饰模式通过将对象包装到装饰器对象中,从而动态地添加新的行为或功能。

角色

角色 说明
Component 抽象构件
ConcreteComponent 具体构件
Decorator 抽象装饰类
ConcreteDecorator 具体装饰类

角色示例

类名 担任角色 说明
SocialSoftware 抽象构件 社交软件
Wechat 具体构件 微信
SetWechat 抽象装饰类 微信设置
Voice 具体装饰类 语音
Video 具体装饰类 视频

UML类图

装饰模式.jpg

代码

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
43
<?php
abstract class SocialSoftware
{
abstract function chat();
}

class Wechat extends SocialSoftware
{
public function chat() {
return '聊天';
}
}

class SetWechat extends SocialSoftware {
protected $wechat;

protected $special;

function __construct($wechat) {
$this->wechat = $wechat;
}

public function chat() {
return $this->special.$this->wechat->chat();
}
}

class Voice extends SetWechat {
protected $special = '语音';
}

class Video extends SetWechat {
protected $special = '视频';
}

$wechat = new Wechat();
echo $wechat->chat().PHP_EOL;

$wechat = new Voice($wechat);
echo $wechat->chat().PHP_EOL;

$wechat = new Video($wechat);
echo $wechat->chat().PHP_EOL;

创建 Wechat.php,内容如上。

执行

1
2
3
4
$ php Wechat.php
聊天
语音聊天
视频语音聊天
-------------本文结束感谢您的阅读-------------
0%