組合模式:針對“部分-整體”的階層,使得使用者對單個對象和組合對象的使用具有一致性。
#encoding=utf-8##by panda#組合模式def printInfo(info): print unicode(info, 'utf-8').encode('gbk')#Component:公司抽象類別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): #履行職責 pass #Composite:公司類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): #履行職責 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): #履行職責 printInfo('%s\t員工招聘培訓管理' % 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): #履行職責 printInfo('%s\t公司財務收支管理' % self.name)def clientUI(): root = ConcreteCompany('北京總公司') root.Add(HRDepartment('總公司人力資源部')) root.Add(FinanceDepartment('總公司財務部')) comp = ConcreteCompany('華東分公司') comp.Add(HRDepartment('華東分公司人力資源部')) comp.Add(FinanceDepartment('華東分公司財務部')) root.Add(comp) comp1 = ConcreteCompany('南京辦事處') comp1.Add(HRDepartment('南京辦事處人力資源部')) comp1.Add(FinanceDepartment('南京辦事處財務部')) comp.Add(comp1) comp2 = ConcreteCompany('杭州辦事處') comp2.Add(HRDepartment('杭州辦事處人力資源部')) comp2.Add(FinanceDepartment('杭州辦事處財務部')) comp.Add(comp2) printInfo('-------公司結構圖-------') root.Display(1) printInfo('\n-------職責-------') root.LineOfDuty() returnif __name__ == '__main__': clientUI();
類圖: