首页 > 代码库 > 中介者模式

中介者模式

模式说明

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

模式结构图

程序示例

说明:房主、租客与中介

代码:

class Mediator(object):    def sendmsg(self,msg,person):        passclass 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):    passclass Tenant(Person):    passclass 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

 

中介者模式