-
Notifications
You must be signed in to change notification settings - Fork 0
/
decorator_pattern.py
103 lines (49 loc) · 1.18 KB
/
decorator_pattern.py
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
'''
装饰器模式
通过装饰器,在不修改原有对象的前提下,对原有对象的功能进行扩展。
'''
import abc
class Component(abc.ABC):
"""对象操作的接口。"""
@abc.abstractmethod
def operate(self):
pass
class OriObject(Component):
"""原有对象"""
def operate(self):
print('Original Object')
class Decorator(Component):
"""装饰器 基类"""
def decorator(self, component):
self.component = component
def operate(self):
if self.component:
self.component.operate()
class DecoratorA(Decorator):
"""装饰器 A"""
def operate(self):
super().operate()
print('Decorator A operating...')
class DecoratorB(Decorator):
"""装饰器 B"""
def operate(self):
super().operate()
print('Decorator B ~~~')
class DecoratorC(Decorator):
"""装饰器 C"""
def operate(self):
super().operate()
print('Decorator C working...')
if __name__ == '__main__':
ori = OriObject()
decA = DecoratorA()
decB = DecoratorB()
decC = DecoratorC()
decA.decorator(ori)
decB.decorator(decA)
decC.decorator(decB)
decC.operate()
print('----------------')
decC.decorator(ori)
decA.decorator(decC)
decA.operate()