-
Notifications
You must be signed in to change notification settings - Fork 1
/
17-装饰器模式.php
91 lines (77 loc) · 1.51 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
declare(strict_types=1);
/*
* This file is modified from `xiaohuangniu/26`.
*
* @see https://github.com/xiaohuangniu/26
*/
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}标志 ".PHP_EOL;
}
}
echo '未加装饰器之前:';
// 生产运动鞋
$shoesSport = new ShoesSport();
$shoesSport->product();
echo PHP_EOL;
echo '加贴标装饰器:';
// 初始化一个贴商标适配器
$DecoratorBrand = new DecoratorBrand($shoesSport);
// 写入标签名
$DecoratorBrand->_value = 'nike';
// 生产nike牌运动鞋
$DecoratorBrand->product();