Combine , Combine multiple objects into a tree structure , To represent the level of business logic . The composition mode makes the use of single object and composite object consistent .
such as , Describe the hierarchy of a company , Then we use offices to represent nodes , Then the general manager's office is the root node , The personnel office 、 Business office 、 Production office 、 The finance office , There can be smaller offices under each office , Every office has responsibilities 、 Number of personnel 、 Personnel salary and other attributes ;
advantage :
Entity role :
class ComponentBase:
""" The base class abstracted from the Department """
def __init__(self, name):
slef.name = name
def add(self, obj):
pass
def remove(self, obj):
pass
def display(self, number):
pass
class Node(ComponentBase):
def __init__(self, name, duty):
self.name = name
self.duty = duty
self.children = []
def add(self, obj):
self.children.append(obj)
def remove(self, obj):
self.children.remove(obj)
def display(self, number=1):
print(" department :{} Level :{} duty :{}".format(self.name, number, self.duty))
n = number+1
for obj in self.children:
obj.display(n)
if __name__ == '__main__':
root = Node(" General Manager's Office ", " General manager ")
node1 = Node(" The financial department ", " Corporate financial management ")
root.add(node1)
node2 = Node(" Business unit ", " Selling products ")
root.add(node2)
node3 = Node(" Production department ", " Production of products ")
root.add(node3)
node4 = Node(" Sales Department ", "A Product sales ")
node2.add(node4)
node5 = Node(" Sales Department II ", "B Product sales ")
node2.add(node5)
root.display()