程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python design pattern - structural pattern - composite pattern

編輯:Python

Catalog

List of articles

  • Catalog
  • Portfolio model
  • Application scenarios
  • Code example

Portfolio model

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

  • Defines a class hierarchy that contains basic and composite objects .
  • simplify Client Code , namely Client You can use composite objects and single objects consistently .
  • It's easier to add new types of components .

Application scenarios

  • Used to design a hierarchical system , And deal with the relationship between all levels .

Code example

Entity role :

  • Abstract components (Component)
  • Leaf assembly (Leaf)
  • Composite components (Composite)
  • client (Client)
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()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved