-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathDecorator.php
86 lines (72 loc) · 1.85 KB
/
Decorator.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
<?php
/*
* 装饰者模式:动态地将责任附加到对象上
*
* 在装饰者模式中,装饰者和被装饰者继承自同一个类。装饰者会持有一个被装饰者的对象,在方法中通过在调用被装饰者相应方法的前后添加自己的逻辑,从而达到添加功能的目的。装饰者模式提供了一种类似于继承的另一种扩展方式
*
* 在此示例中,具体Human和HumanDecorator同属Human抽象类。装饰者会持有一个Human实例,在HumanDecorator调用display时会在调用Human的display方法的前后包装一层自己的逻辑,从而达到扩展功能的目的。
*
*
*/
abstract class Human
{
abstract public function display();
}
class YellowHuman extends Human
{
public function display()
{
echo "YellowHuman";
}
}
class BlackHuman extends Human
{
public function display()
{
echo "BlackHuman";
}
}
abstract class HumanDecorator extends Human
{
protected $human;
public function __construct(Human $human)
{
$this->human = $human;
}
}
class WatchDecorator extends HumanDecorator
{
public function display()
{
echo $this->human->display()." with a Watch";
}
}
class GlassesDecorator extends HumanDecorator
{
public function display()
{
echo $this->human->display()." with a Glasses";
}
}
class Test
{
public function run()
{
$yellowHuman = new YellowHuman();
$blackHuman = new BlackHuman();
$yellowHumanWithWatch = new WatchDecorator($yellowHuman);
$blackHumanWithGlasses = new GlassesDecorator($blackHuman);
$yellowHumanWithWatchWithGlasses = new GlassesDecorator($yellowHumanWithWatch);
$yellowHuman->display();
echo "<br>\n";
$blackHuman->display();
echo "<br>\n";
$yellowHumanWithWatch->display();
echo "<br>\n";
$blackHumanWithGlasses->display();
echo "<br>\n";
$yellowHumanWithWatchWithGlasses->display();
}
}
$test = new Test();
$test->run();