中介者模式(python)

"""
中介者模式
用一个中介对象封装一系列对象的交互,使各对象不再需要显示互相引用,减少了对象间的耦合
把对象的交互抽象到了一个中介对象中,我们可以把注意力从对象行为转移到对象的交互上,可以更宏观的看待对象问题
从网状结构变成星型结构
应用场景:各对象已定义良好,但是对象间有复杂的通讯
"""
from abc import ABCMeta, abstractmethod


class Unit(object):
    __metaclass__ = ABCMeta

    def __init__(self):
        pass

    @abstractmethod
    def declare(self, count, message):
        pass


class Nations(Unit):
    def __init__(self):
        super(Nations, self).__init__()
        self._china = None
        self._american = None

    def set_china(self, china):
        self._china = china

    def set_american(self, american):
        self._american = american

    def declare(self, country, message):
        if self._china.name == country.name:
            self._american.get_message(message)
        elif self._american.name == country.name:
            self._china.get_message(message)


class Country(object):
    __metaclass__ = ABCMeta

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

    @abstractmethod
    def declare(self, message):
        pass

    @abstractmethod
    def get_message(self, msg):
        pass


class China(Country):
    def __init__(self, name, nations):
        super(China, self).__init__(name, nations)

    def declare(self, message):
        self.nations.declare(self, message)

    def get_message(self, msg):
        print(msg)


class American(Country):
    def __init__(self, name, nations):
        super(American, self).__init__(name, nations)

    def declare(self, message):
        self.nations.declare(self, message)

    def get_message(self, msg):
        print(msg)

if __name__ == '__main__':
    nations = Nations()
    china = China("中国", nations)
    american = American("美国", nations)
    nations.set_china(china)
    nations.set_american(american)

    china.declare("美国你给我注意点,我要打你了")
    print("")
    american.declare("打死我吧")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值