设计模式之十--组合模式

组合模式:将对象组合成熟型结构一表示‘部分-整体’的层次结构。组合模式使得用户对单个对象的组合对象的使用具有一致性。具体来讲就是,树根和树枝和树叶都是统一对待的。树枝和树叶继承于树根。

什么时候用组合模式?
当需求中是体现部分与整体的层次结构式,以及你希望用户可以忽略组合对象与单个对象的不同,统一使用组合结构中的所有对象时,就应该考虑用组合模式。好了,上代码。

from abc import ABCMeta, abstractmethod


class Company(metaclass=ABCMeta):

    def __init__(self, name):
        self.name = name

    @abstractmethod
    def add(self, company):
        pass

    @abstractmethod
    def remove(self, company):
        pass

    @abstractmethod
    def display(self, depth):
        pass

    @abstractmethod
    def line_of_duty(self):
        pass


class ConcreteCompany(Company):

    def __init__(self, name):
        super().__init__(name)
        self.children = []

    def add(self, company):
        self.children.append(company)

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

    def display(self, depth):
        print('-'*depth + "Company {0}".format(self.name))
        for company in self.children:
            company.display(depth + 2)

    def line_of_duty(self):
        for company in self.children:
            company.line_of_duty()


class HRDepartment(Company):

    def __init__(self, name):
        super().__init__(name)

    def add(self, company):
        pass

    def remove(self, company):
        pass

    def display(self, depth):
        print('-'*depth + self.name)

    def line_of_duty(self):
        print("{0} This department is responsible for recruiting employees".format(self.name))


class FinanceDepartment(Company):

    def __init__(self, name):
        super().__init__(name)

    def add(self, company):
        pass

    def remove(self, company):
        pass

    def display(self, depth):
        print('-'*depth + self.name)

    def line_of_duty(self):
        print("{0} This department is responsible for managing the money".format(self.name))


if __name__ == "__main__":

    headquarter = ConcreteCompany("Headquarter")
    headquarter.add(HRDepartment("Root HR"))
    headquarter.add(FinanceDepartment("Root Finance"))

    south_subsidy = ConcreteCompany("SouthSubsidy")
    south_subsidy.add(HRDepartment("SouthSubsidy HR Department"))
    south_subsidy.add(FinanceDepartment("SouthSubsidy Finance Department"))
    headquarter.add(south_subsidy)

    north_subsidy = ConcreteCompany("NorthSubsidy")
    north_subsidy.add(HRDepartment("NorthSubsidy HR Department"))
    north_subsidy.add(FinanceDepartment("NorthSubsidy Finance Department"))
    headquarter.add(north_subsidy)

    headquarter.display(1)
    headquarter.line_of_duty()

这段代码中,优点浪费的是,具体的部门类,也就是树叶,里边为了统一性会有一部分的代码没有实现。也可以把这些去掉。在Comany类中不写这两个接口,只在ConcreteCompany 类中实现add remove等操作,但是这样在使用这些类的时候, 由于树叶和树枝接口不同,就需要有一些判断。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值