python 设计模式(十二) 组合模式(composite pattern)

组合模式的经典定义:将对象组合成成树形结构以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性. 

举例如下:学校里的教员包括校长,也包括年级主任,也包括普通的学科老师。校长管理年级主任和普通老师,普通老师又被年级主任管理者。下面实现了staff抽象类,teacher(教员)和director(校长和年级主任)都继承自staff抽象类。具体实现如下:

import abc


class Staff(object):
    """
    抽象类
    """
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def add_people(self, *args, **kwargs):
        pass

    @abc.abstractmethod
    def remove_people(self, *args, **kwargs):
        pass

    @abc.abstractmethod
    def work(self, *args, **kwargs):
        pass


class Teacher(Staff):
    def __init__(self, name):
        self.name = name

    def add_people(self):
        print('I am a regular teacher, no man at my hand')

    def remove_people(self):
        print('no man at my hand')

    def work(self):
        print('regular teacher %s start working' % self.name)


class Director(Staff):
    def __init__(self, name):
        self.name = name
        self.members = []

    def add_people(self, teacher):
        self.members.append(teacher)

    def remove_people(self, teacher):
        self.members.remove(teacher)

    def work(self):
        print('director %s start working' % self.name)
        for member in self.members:
            member.work()


class Client(object):
    def __init__(self, teacher):
        self.teacher = teacher

    def work(self):
        self.teacher.work()

if __name__ == '__main__':
    director = Director('laoguo')
    director1 = Director('laoliu')
    teacher1 = Teacher('laoxie')
    teacher2 = Teacher('laoding')
    director1.add_people(teacher1)
    director1.add_people(teacher2)
    director.add_people(director1)
    client = Client(director)
    client.work()
    print('*'*100)
    client.teacher = director1
    client.work()
    print('*'*100)
    client.teacher = teacher1
    client.work()

结果如下:

director laoguo start working
director laoliu start working
regular teacher laoxie start working
regular teacher laoding start working
****************************************************************************************************
director laoliu start working
regular teacher laoxie start working
regular teacher laoding start working
****************************************************************************************************
regular teacher laoxie start working

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