-
Notifications
You must be signed in to change notification settings - Fork 0
/
composite_base.py
96 lines (67 loc) · 2.12 KB
/
composite_base.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
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List
class Component(ABC):
@property
def parent(self) -> Component:
return self._parent
@parent.setter
def parent(self, parent: Component):
self._parent = parent
def add(self, component: Component) -> None:
pass
def remove(self, component: Component) -> None:
pass
def is_composite(self) -> bool:
return False
@abstractmethod
def operation(self) -> str:
pass
class Leaf(Component):
def operation(self) -> str:
return "Leaf"
class Composite(Component):
def __init__(self) -> None:
self._children: List[Component] = []
def add(self, component: Component) -> None:
self._children.append(component)
component.parent = self
def remove(self, component: Component) -> None:
self._children.remove(component)
component.parent = None
def is_composite(self) -> bool:
return True
def operation(self) -> str:
results = []
for child in self._children:
results.append(child.operation())
return " ".join(results)
def client_code(component: Component) -> None:
print(f"RESULT: {component.operation()}", end="")
def client_code2(component1: Component, component2: Component) -> None:
if component1.is_composite():
component1.add(component2)
print(f"RESULT: {component1.operation()}", end="")
if __name__ == "__main__":
simple = Leaf()
print("Client: I've got a simple component:")
client_code(simple)
print("\n")
tree = Composite()
branch1 = Composite()
branch1.add(Leaf())
branch1.add(Leaf())
branch2 = Composite()
branch2.add(Leaf())
tree.add(branch1)
tree.add(branch2)
print("Client: Now I've got a composite tree:")
client_code(tree)
print("\n")
client_code2(tree, Leaf())
print("\n")
client_code2(tree, Composite())
print("\n")
print("Client: I don't need to check the components classes even then managing the tree:")
client_code2(tree, simple)
print("\n")