設計模式之十四--中介者模式

中介者模式:由一箇中介者對象來封裝一些列的對象交。中介者使各對象不需要顯式地相互引用,從而使其耦合鬆散,而且可以獨立地改變他們之間的交互。

中介者模式的優點和缺點,都在於集中式的管理,所有的邏輯都集中於中介者類,可能會造成邏輯過於複雜。

from abc import ABCMeta, abstractmethod


class Mediator(metaclass=ABCMeta):

    @abstractmethod
    def send_message(self, young_people, message):
        pass


class ConcreteMediator(Mediator):

    def __init__(self):
        self.__young_girl = None
        self.__young_boy = None

    @property
    def young_girl(self):
        return self.__young_girl

    @young_girl.setter
    def young_girl(self, girl):
        self.__young_girl = girl

    @property
    def young_boy(self):
        return self.__young_boy

    @young_boy.setter
    def young_boy(self, boy):
        self.__young_boy = boy

    def send_message(self, young_people, message):
        if isinstance(young_people, Girl):
            self.__young_boy.notify(message)

        if isinstance(young_people, Boy):
            self.__young_girl.notify(message)


class YoungPeople(metaclass=ABCMeta):

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

    @abstractmethod
    def send_message(self, message):
        pass

    @abstractmethod
    def notify(self, message):
        pass


class Girl(YoungPeople):

    def __init__(self, mediator):
        super(Girl, self).__init__(mediator)

    def notify(self, message):
        print("The girl got the message {0}".format(message))

    def send_message(self, message):
        self.mediator.send_message(self, message)


class Boy(YoungPeople):

    def __init__(self, mediator):
        super(Boy, self).__init__(mediator)

    def send_message(self, message):
        self.mediator.send_message(self, message)

    def notify(self, message):
        print("The boy got the message {0}".format(message))


if __name__ == "__main__":
    mediator = ConcreteMediator()

    girl = Girl(mediator)
    boy = Boy(mediator)

    mediator.young_girl = girl
    mediator.young_boy = boy

    boy.send_message("Do you wanna date with me?")
    girl.send_message("Really? I do.")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章