-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomposite.py
83 lines (61 loc) · 1.69 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
72
73
74
75
76
77
78
79
80
81
82
83
# --------------------------------------------------------
# Licensed under the terms of the BSD 3-Clause License
# (see LICENSE for details).
# Copyright © 2018-2024, A.A Suvorov
# All rights reserved.
# --------------------------------------------------------
# https://github.com/smartlegionlab/
# --------------------------------------------------------
"""Composite"""
from abc import ABC
class Graphic(ABC):
def draw(self):
raise NotImplementedError
def add(self, obj):
raise NotImplementedError
def remove(self, obj):
raise NotImplementedError
def get_child(self, index):
raise NotImplementedError
class Line(Graphic, ABC):
def draw(self):
print('Line')
class Rectangle(Graphic, ABC):
def draw(self):
print('Rectangle')
class Text(Graphic, ABC):
def draw(self):
print('Text')
class Picture(Graphic):
def __init__(self):
self._children = []
def add(self, obj):
if isinstance(obj, Graphic) and obj not in self._children:
self._children.append(obj)
else:
raise TypeError
def remove(self, obj):
if obj in self._children:
index = self._children.index(obj)
del self._children[index]
def draw(self):
for obj in self._children:
obj.draw()
def get_child(self, index):
return self._children[index]
def main():
pic = Picture()
pic.add(Line())
pic.add(Rectangle())
pic.add(Text())
pic.draw()
child = pic.get_child(0)
print(isinstance(child, Line)) # True
if __name__ == '__main__':
# Output:
# -------
# Line
# Rectangle
# Text
# True
main()