-
Notifications
You must be signed in to change notification settings - Fork 27
/
17、装饰器模式.php
71 lines (67 loc) · 1.4 KB
/
17、装饰器模式.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
<?php
/**
* 设计模式之装饰器模式
* 场景:在不改动类文件的前提上,对类进行功能上的扩展
* 小黄牛
*/
header("Content-type: text/html; charset=utf-8");
/**
* 接口 - 鞋
*/
interface ShoesInterface{
public function product();
}
/**
* 创建 - 运动鞋模型
*/
class ShoesSport implements ShoesInterface{
public function product(){
echo "生产一双球鞋";
}
}
/**
* 抽象 - 装饰器类
*/
abstract class Decorator implements ShoesInterface{
protected $shoes; // 模型的实例
public function __construct($shoes){
$this->shoes = $shoes;
}
# 生成方法
public function product(){
$this->shoes->product();
}
#定义装饰操作
abstract public function decorate();
}
/**
* 创建 - 贴标装饰器
*/
class DecoratorBrand extends Decorator{
public $_value; // 标签名
/**
* 生成操作
*/
public function product(){
$this->shoes->product();
$this->decorate();
}
/**
* 贴标操作
*/
public function decorate(){
echo "贴上{$this->_value}标志 <br/>";
}
}
echo "未加装饰器之前:";
# 生产运动鞋
$shoesSport = new ShoesSport();
$shoesSport->product();
echo "<br/>";
echo "加贴标装饰器:";
# 初始化一个贴商标适配器
$DecoratorBrand = new DecoratorBrand($shoesSport);
# 写入标签名
$DecoratorBrand->_value = 'nike';
# 生产nike牌运动鞋
$DecoratorBrand->product();