zoukankan      html  css  js  c++  java
  • 中介者模式

    模式说明

    所谓中介者模式就是用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。

    模式结构图

    程序示例

    说明:房主、租客与中介

    代码:

    class Mediator(object):
        def sendmsg(self,msg,person):
            pass
    
    class Person(object):
        def __init__(self,name,mediator):
            self._name = name
            self._mediator = mediator
        def contact(self,msg):
            self._mediator.sendmsg(msg,self)
        def getmsg(self,msg):
            print ' %s get msg : %s' % (self._name,msg)
    
    class HouseOwner(Person):
        pass
    class Tenant(Person):
        pass
    
    class ConcreteMediator(Mediator):
        def sethouseowner(self,houseowner):
            self._houseowner = houseowner
        def settenant(self,tenant):
            self._tenant = tenant
    
        def sendmsg(self,msg,person):
            if person != self._houseowner:
                self._houseowner.getmsg(msg)
            else:
                self._tenant.getmsg(msg)
    
    if __name__ == '__main__':
        mediator = ConcreteMediator()
        #house owner find the mediator
        houseowner = HouseOwner('wang',mediator)
        #tenant find the mediator
        tenant = Tenant('li',mediator)
    
        #the mediator make the bridge between houser owner and tenant
        mediator.sethouseowner(houseowner)
        mediator.settenant(tenant)
    
        #houser owner and tenant can contact
        tenant.contact('any else houses?')
        houseowner.contact('yes!')
        print 'over!'
    
        houseowner1 = HouseOwner('chen',mediator)
        mediator.sethouseowner(houseowner1)
    
        tenant.contact('any else houses?')
        houseowner1.contact('yes!')
    
        houseowner.contact('yes!') # not the current houseowner,take as tenant
        

    运行结果:

    参考来源:

    http://www.cnblogs.com/chenssy/p/3679190.html

    http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html

  • 相关阅读:
    QT学习1
    时域和频域
    win10 + VS2017 + MNN 编译使用
    深度学习笔记(二十二)Structure-Preserving Neural Style Transfer
    miRNA分析
    mRNA分析
    代谢组学分析
    实证分析
    React---新扩展RenderProps和ErrorBoundary
    React---新扩展Context和组件优化
  • 原文地址:https://www.cnblogs.com/cotton/p/3935165.html
Copyright © 2011-2022 走看看