forked from amirbigg/python-design-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomposite.py
More file actions
86 lines (58 loc) · 1.33 KB
/
composite.py
File metadata and controls
86 lines (58 loc) · 1.33 KB
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
"""
Composite
- a structural design pattern that lets you compose objects into tree structures
and then work with these structures as if they were individual objects.
"""
import abc
class Being(abc.ABC): # Abstract Component
def add(self, child):
pass
def remove(self, child):
pass
def is_composite(self):
return False
@abc.abstractmethod
def execute(self):
pass
class Animal(Being): # Leaf
def __init__(self, name):
self.name = name
def execute(self):
print(f'Animal {self.name}')
class Human(Being): # Concrete Composite
def __init__(self):
self._children = []
def add(self, child):
self._children.append(child)
def remove(self, child):
self._children.remove(child)
def is_composite(self):
return True
def execute(self):
print('Human Composite')
for child in self._children:
child.execute()
class Male(Human): # Leaf
def __init__(self, name):
self.name = name
def is_composite(self):
return False
def execute(self):
print(f'\tMale {self.name}')
class Female(Human): # Leaf
def __init__(self, name):
self.name = name
def is_composite(self):
return False
def execute(self):
print(f'\tFemale {self.name}')
def client_composite():
f1 = Female('jane')
f2 = Female('katty')
m1 = Male('brad')
h1 = Human()
h1.add(f1)
h1.add(f2)
h1.add(m1)
h1.execute()
client_composite()