-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecorate.php
78 lines (61 loc) · 1.53 KB
/
decorate.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
<?php
/**
* 装饰器模式 不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能
* Created by PhpStorm.
* User: wangyuan
* Date: 18-2-7
* Time: 下午4:32
*/
interface Component{
public function operation();
}
//具体装饰的对象
class ConcreteComponent implements Component{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function operation()
{
// TODO: Implement operation() method.
echo "装饰了".$this->name;
}
}
//装饰器的父类
class DecoratorParent implements Component{
protected $component = null;
//装饰
public function decorator(Component $component){
$this->component = $component;
}
public function operation()
{
// TODO: Implement operation() method.
if (!empty($this->component)){
$this->component->operation();
}
}
}
//具体的装饰器
class DecoratorA extends DecoratorParent{
public function operation()
{
echo 'A装饰器';
parent::operation();
}
}
class DecoratorB extends DecoratorParent{
public function operation()
{
echo "B装饰器";
parent::operation(); // TODO: Change the autogenerated stub
}
}
$person = new ConcreteComponent('test'); //实例化一个装饰对象
$decoratorA = new DecoratorA();
$decoratorB = new DecoratorB();
$decoratorA->decorator($person);
$decoratorB->decorator($person);
$decoratorA->operation();
$decoratorB->operation();