PHP设计模式-装饰器

适用性

  • 对现有的对象增加功能
  • 和适配器的区别:适配器是连接两个接口,装饰器是对现有的对象包装

代码示例

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

/**
* 鞋接口
*/
interface ShoesInterface
{
public function product();
}

/**
* 装饰器抽象类.
*/
abstract class Decorator implements ShoesInterface
{
/**
* 产品生产线对象
*/
protected $shoes;

/**
* 构造函数.
*/
public function __construct(ShoesInterface $shoes)
{
$this->shoes = $shoes;
}

/**
* 生产.
*/
public function product()
{
$this->shoes->product();
}

/**
* 装饰操作.
*/
abstract public function decorate($value);
}

/**
* 贴标装饰器
*/
class DecoratorBrand extends Decorator
{

private $_brand;

/**
* 构造函数
*/
public function __construct(ShoesInterface $phone)
{
$this->phone = $phone;
}

public function __set($name='', $value='')
{
$this->$name = $value;
}

/**
* 生产
*/
public function product()
{
$this->phone->product();
$this->decorate($this->_brand);
}

/**
* 贴标操作
*/
public function decorate($value='')
{
echo "贴上{$value}标志 \n";
}

}

/**
* 滑板鞋实体
*/
class ShoesSkateboard implements ShoesInterface
{
public function product()
{
echo "生产一滑板鞋";
}
}

/**
* 运动鞋实体
*/
class ShoesSport implements ShoesInterface
{
public function product()
{
echo "生产一双球鞋";
}
}


try {
echo "未加装饰器之前:\n";
// 生产运动鞋
$shoesSport = new ShoesSport();
$shoesSport->product();

echo "\n--------------------\n";

echo "加贴标装饰器:\n";
// 初始化一个贴商标适配器
$DecoratorBrand = new DecoratorBrand(new ShoesSport());
$DecoratorBrand->_brand = 'nike';
// 生产nike牌运动鞋
$DecoratorBrand->product();
} catch (\Exception $e) {
echo $e->getMessage();
}