组合模式(python)

"""
组合模式
组合对象成树形结构以表示部分-整体结构
在使用单个对象和组合对象时具有一致性
"""
from abc import ABCMeta, abstractmethod


class Company(object):
    """
    公司抽象类
    """
    __metaclass__ = ABCMeta

    def __init__(self, name, duty):
        self.name = name
        self.zeren = duty
        pass

    @abstractmethod
    def append(self, company):
        pass

    @abstractmethod
    def remove(self, company):
        pass

    @abstractmethod
    def display(self, num):
        pass

    @abstractmethod
    def duty(self):
        pass


class Department(Company):
    def __init__(self, name, duty):
        super(Department, self).__init__(name, duty)

    def append(self, company):
        print("我不能添加子部门")

    def remove(self, company):
        print("我没有子部门删除")

    def display(self, num):
        string = ""
        for i in range(num):
            string += "-"
        print(string + self.name)

    def duty(self):
        print(self.name + "   " + self.zeren)


class ChildCompany(Company):
    def __init__(self, name, duty):
        super(ChildCompany, self).__init__(name, duty)
        self.child_list = []

    def append(self, company):
        self.child_list.append(company)

    def remove(self, company):
        self.child_list.remove(company)

    def display(self, num):
        string = ""
        for i in range(num):
            string += "-"
        print(string + self.name)
        for child in self.child_list:
            child.display(num + 2)

    def duty(self):
        print(self.name + "  " + self.zeren)
        for child in self.child_list:
            child.duty()


if __name__ == '__main__':
    root = ChildCompany("总公司", "管理整个公司")

    renli = Department("人力资源部", "管理总公司人力")
    caiwu = Department("财务部", "管理总公司财务")

    root.append(renli)
    root.append(caiwu)

    shanghai = ChildCompany("上海分公司", "上海事物")
    shanghai_renli = Department("上海人力资源部", "上海人力事务")
    shanghai.append(shanghai_renli)

    hangzhou = ChildCompany("杭州分公司", "杭州事务")
    hangzhou_caiwu = Department("杭州财务部", "杭州财务")
    hangzhou.append(hangzhou_caiwu)

    fujian = Department("福建分公司", "福建事务")
    fujian_xingzhen = Department("福建行政部", "福建行政")
    fujian.append(fujian_xingzhen)

    root.append(shanghai)
    root.append(hangzhou)
    root.append(fujian)
    root.display(1)
    print("")
    root.duty()
    print("")
    print("")

    root.remove(fujian)
    root.display(2)
    print("")
    root.duty()


你可能感兴趣的:(设计模式)