Combination Mode:The "part-whole" hierarchy makes the use of a single object and a composite object consistent.
# Encoding = UTF-8 ## by Panda # combined mode def printinfo (Info): Print Unicode (Info, 'utf-8 '). encode ('gbk') # component: Company Abstract class company: Name = ''def _ init _ (self, name): Self. name = Name def add (self, company): Pass def remove (self, company): Pass def display (self, depth): Pass def lineofduty (Self ): # fulfill duties pass # Composite: Company class concretecompany (company): childrencompany = none def _ init _ (self, name): Company. _ init _ (self, name) self. childrencompany = [] def add (self, company): Self. childrencompany. append (company) def remove (self, company): Self. childrencompany. remove (company) def display (self, depth): printinfo ('-' * depth + self. name) for component in self. childrencompany: component. display (depth + 2) def lineofduty (Self): # perform duties for component in self. childrencompany: component. lineofduty () # leaf: Class hrdepartment (company): def _ init _ (self, name): Company. _ init _ (self, name) def display (self, depth): printinfo ('-' * depth + self. name) def lineofduty (Self): # perform duties printinfo ('% s \ t employee recruitment and training management' % self. name) # leaf: Class financedepartment (company): def _ init _ (self, name): Company. _ init _ (self, name) def display (self, depth): printinfo ('-' * depth + self. name) def lineofduty (Self): # perform duties printinfo ('% s \ t company financial revenue and expenditure management' % self. name) def clientui (): Root = concretecompany ('Beijing head office ') root. add (hrdepartment ('Human resources authorization') root. add (financedepartment ('head office finance ') comp = concretecompany ('East China Branch') comp. add (hrdepartment ('Human resources department of East China Branch ') comp. add (financedepartment ('finance Department of East China Branch ') root. add (COMP) comp1 = concretecompany ('nanjing office ') comp1.add (hrdepartment ('nanjing office human resources authority') comp1.add (financedepartment ('nanjing Office Finance Authority ') comp. add (comp1) comp2 = concretecompany ('hangzhou office ') comp2.add (hrdepartment ('hangzhou office human resources authority') comp2.add (financedepartment ('hangzhou Office Finance Authority ') comp. add (comp2) printinfo ('------- company structure -------') root. display (1) printinfo ('\ n ------- responsibility -------') root. lineofduty () returnif _ name _ = '_ main _': clientui ();
Class Diagram: