-
Notifications
You must be signed in to change notification settings - Fork 1
/
composite.py
77 lines (56 loc) · 2.09 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
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 abstract class Component
'''Concreate class that 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 child items'''
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 composite object
print('{}'.format(self.name))
#Iterate through child objects and inovke their component
#function printing their name
for obj in self.children:
obj.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 compsite menu
top.append_child(sub2)
#Test composite pattern
top.component_function()