組合模式(python)

來源:互聯網
上載者:User

組合模式:針對“部分-整體”的階層,使得使用者對單個對象和組合對象的使用具有一致性。

#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();

類圖

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.