1
+ #
2
+ # Python Design Patterns: Composite
3
+ # Author: Jakub Vojvoda [github.com/JakubVojvoda]
4
+ # 2016
5
+ #
6
+ # Source code is licensed under MIT License
7
+ # (for more details see LICENSE)
8
+ #
9
+
10
+ import sys
11
+
12
+ #
13
+ # Component
14
+ # defines an interface for all objects in the composition
15
+ # both the composite and the leaf nodes
16
+ #
17
+ class Component :
18
+ def getChild (self , index ):
19
+ pass
20
+
21
+ def add (self , component ):
22
+ pass
23
+
24
+ def remove (self , index ):
25
+ pass
26
+
27
+ def operation (self ):
28
+ pass
29
+
30
+ #
31
+ # Composite
32
+ # defines behavior of the components having children
33
+ # and store child components
34
+ #
35
+ class Composite (Component ):
36
+ def __init__ (self ):
37
+ Component .__init__ (self )
38
+ self ._children = []
39
+
40
+ def getChild (self , index ):
41
+ return self ._children [index ]
42
+
43
+ def add (self , component ):
44
+ self ._children .append (component )
45
+
46
+ def remove (self , index ):
47
+ self ._children .remove (index )
48
+
49
+ def operation (self ):
50
+ for i in range (len (self ._children )):
51
+ self ._children [i ].operation ()
52
+
53
+ #
54
+ # Leaf
55
+ # defines the behavior for the elements in the composition,
56
+ # it has no children
57
+ #
58
+ class Leaf (Component ):
59
+ def __init__ (self , index ):
60
+ Component .__init__ (self )
61
+ self ._idx = index
62
+
63
+ def operation (self ):
64
+ print ("Leaf " + str (self ._idx ) + " operation." )
65
+
66
+
67
+ if __name__ == "__main__" :
68
+ composite = Composite ()
69
+
70
+ for i in range (5 ):
71
+ composite .add (Leaf (i ))
72
+
73
+ composite .operation ()
0 commit comments