码迷,mamicode.com
首页 > 其他好文 > 详细

中介者模式

时间:2014-08-25 16:40:26      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   ar   2014   div   代码   html   

模式说明

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

模式结构图

bubuko.com,布布扣

程序示例

说明:房主、租客与中介

代码:

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
    

运行结果:

bubuko.com,布布扣

参考来源:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!