-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathcomposite.py
More file actions
62 lines (49 loc) · 1.52 KB
/
composite.py
File metadata and controls
62 lines (49 loc) · 1.52 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
"""
Composite
- A mechanism for treating individual (scalar) objects and composition of
objects in a uniform matter
Motivation
- Objects use others' properties/members through inheritance and composition
- Composition lets us make compound objects
- E.g., a mathematical expression composed of simple expressions; or
- A grouping of shapes that consists of several shapes
- Composite design pattern is used to treat both single (scalar) and composite
objects uniformly
- I.e., Foo and Sequence (yielding Foo's) have common APIs
"""
class GraphicObject:
def __init__(self, color=None):
self.color = color
self.children = []
self._name = 'Group'
@property
def name(self):
return self._name
def _print(self, items, depth):
items.append('*' * depth)
if self.color:
items.append(self.color)
items.append(f'{self.name}\n')
for child in self.children:
child._print(items, depth + 1)
def __str__(self):
items = []
self._print(items, 0)
return ''.join(items)
class Circle(GraphicObject):
@property
def name(self):
return 'Circle'
class Square(GraphicObject):
@property
def name(self):
return 'Square'
DRAWING = GraphicObject()
DRAWING._name = 'My Drawing'
DRAWING.children.append(Square('Red'))
DRAWING.children.append(Circle('Yellow'))
GROUP = GraphicObject()
GROUP.children.append(Circle('Blue'))
GROUP.children.append(Square('Blue'))
DRAWING.children.append(GROUP)
print(DRAWING)