-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcomposite.py
More file actions
61 lines (43 loc) · 1011 Bytes
/
Copy pathcomposite.py
File metadata and controls
61 lines (43 loc) · 1011 Bytes
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
#!/usr/bin/env python
"""
组合模式
"""
from abc import ABCMeta
class BaseClass(metaclass=ABCMeta):
def __init__(self, name):
self.name = name
self.sub = []
def show(self):
for item in self.sub:
print(item.name)
class Root(BaseClass):
def __init__(self, name):
super().__init__(name)
self.sub = []
def add(self, branch):
self.sub.append(branch)
class Branch(BaseClass):
def __init__(self, name):
super().__init__(name)
self.sub = []
def add(self, leaf):
self.sub.append(leaf)
class Leaf(BaseClass):
def __init__(self, name):
super().__init__(name)
if __name__ == "__main__":
root = Root("tree")
bra = Branch("bra")
brb = Branch("brb")
lea = Leaf("lea")
leb = Leaf("leb")
lec = Leaf("lec")
led = Leaf("led")
bra.add(lea)
bra.add(leb)
brb.add(lec)
brb.add(led)
root.add(bra)
root.add(brb)
root.show()
bra.show()