-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomposite_final.py
More file actions
executable file
·79 lines (55 loc) · 2.03 KB
/
composite_final.py
File metadata and controls
executable file
·79 lines (55 loc) · 2.03 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class Component(object):
"""Abstract class"""
def __init__(self, *args, **kwargs):
pass
def component_function(self):
pass
class Child(Component): #Inherits from the abstract class, Component
"""Concrete class"""
def __init__(self, *args, **kwargs):
Component.__init__(self, *args, **kwargs)
#This is where we store the name of your child item!
self.name = args[0]
def component_function(self):
#Print the name of your child item here!
print("{}".format(self.name))
class Composite(Component): #Inherits from the abstract class, Component
"""Concrete class and maintains the tree recursive structure"""
def __init__(self, *args, **kwargs):
Component.__init__(self, *args, **kwargs)
#This is where we store the name of the composite object
self.name = args[0]
#This is where we keep our child items
self.children = []
def append_child(self, child):
"""Method to add a new child item"""
self.children.append(child)
def remove_child(self, child):
"""Method to remove a child item"""
self.children.remove(child)
def component_function(self):
#Print the name of the composite object
print("{}".format(self.name))
#Iterate through the child objects and invoke their component function printing their names
for i in self.children:
i.component_function()
#Build a composite submenu 1
sub1 = Composite("submenu1")
#Create a new child sub_submenu 11
sub11 = Child("sub_submenu 11")
#Create a new Child sub_submenu 12
sub12 = Child("sub_submenu 12")
#Add the sub_submenu 11 to submenu 1
sub1.append_child(sub11)
#Add the sub_submenu 12 to submenu 1
sub1.append_child(sub12)
#Build a top-level composite menu
top = Composite("top_menu")
#Build a submenu 2 that is not a composite
sub2 = Child("submenu2")
#Add the composite submenu 1 to the top-level composite menu
top.append_child(sub1)
#Add the plain submenu 2 to the top-level composite menu
top.append_child(sub2)
#Let's test if our Composite pattern works!
top.component_function()