首页 > 代码库 > 中介者模式
中介者模式
模式说明
所谓中介者模式就是用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
模式结构图
程序示例
说明:房主、租客与中介
代码:
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
中介者模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。