-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathComposite.py
71 lines (48 loc) · 1.59 KB
/
Composite.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
from abc import ABC, abstractmethod
from typing import Set
class Component(ABC):
"""
The base Component class declares common operations for both simple and
complex objects of a composition.
"""
@abstractmethod
def price(self) -> float:
pass
class Product(Component):
def __init__(self, price: float) -> None:
self._price = price
@property
def price(self) -> float:
return self._price
class Box(Component):
def __init__(self, price: float) -> None:
self._price = price
self._components: Set[Component] = set()
def add(self, component: Component) -> None:
self._components.add(component)
def remove(self, component: Component) -> None:
self._components.remove(component)
@property
def price(self) -> float:
totalPrice = self._price
for product in self._components:
totalPrice += product.price
return totalPrice
def client_code(component: Component) -> None:
print(f"Component price: {component.price:.2f} €")
if __name__ == "__main__":
# The client code can support the simple Product components...
simple = Product(11.2)
print("\nClient: I've got a simple component:")
client_code(simple)
# ...as well as complex composites
box = Box(1.25)
smallerBox1 = Box(0.8)
smallerBox1.add(Product(4.25))
smallerBox1.add(Product(1.3))
smallerBox2 = Box(0.5)
smallerBox2.add(Product(2.05))
box.add(smallerBox1)
box.add(smallerBox2)
print("\nClient: I've got a complex composite component:")
client_code(box)