-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomposite.py
58 lines (45 loc) · 1.1 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
from abc import ABC, abstractmethod
# Component
class Graphic(ABC):
@abstractmethod
def draw(self):
pass
# Leaf
class Circle(Graphic):
def draw(self):
print("Circle")
# Leaf
class Square(Graphic):
def draw(self):
print("Square")
# Composite
class CompositeGraphic(Graphic):
def __init__(self):
self.children = [] # components
def add(self, graphic): # add component
self.children.append(graphic)
def remove(self, graphic): # remove component
self.children.remove(graphic)
def draw(self):
for child in self.children:
child.draw()
# Client code
def client_code(graphic):
graphic.draw()
# Usage
circle1 = Circle()
circle2 = Circle()
square1 = Square()
composite1 = CompositeGraphic()
composite1.add(circle1)
composite1.add(circle2)
composite2 = CompositeGraphic()
composite2.add(square1)
composite2.add(composite1)
print("Client: Drawing a composite graphic with nested components:")
client_code(composite2)
## Output
# Client: Drawing a composite graphic with nested components:
# Square
# Circle
# Circle