标签:style blog http color ar 2014 div 代码 html
所谓中介者模式就是用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
说明:房主、租客与中介
代码:
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
标签:style blog http color ar 2014 div 代码 html
原文地址:http://www.cnblogs.com/wang-shuai/p/3935165.html