中介者模式:用一個中介對象來封裝一系列的對象互動。中介者使各對象不需要顯式地相互引用,從而使其耦合鬆散,而且可以獨立地改變它們之間的互動。
一般應用於一組對象以定義良好但是複雜的方式進行通訊的場合。
優點:降低了各個模組的耦合性。
缺點:中介對象容易變得複雜和龐大。
#encoding=utf-8##by panda#中介者模式def printInfo(info): print unicode(info, 'utf-8').encode('gbk')#抽象中介者class Mediator(): def Send(self, message, colleague): pass#抽象同事類class Colleague(): mediator = None def __init__(self,mediator): self.mediator = mediator #具體同事類class ConcreteColleague(Colleague): name = '' def __init__(self, name, mediator): self.name = name Colleague.__init__(self,mediator) def Send(self,message): self.mediator.Send(message, self) def Notify(self,message): printInfo('%s得到對方訊息:%s' % (self.name, message)) #具體中介者class ConcreteMediator(Mediator): name = '' colleague1 = None colleague2 = None def __init__(self, name): self.name = name def Send(self, message, colleague): if colleague == self.colleague1: self.colleague2.Notify(message) else: self.colleague1.Notify(message)def clientUI(): mediator = ConcreteMediator('聯合國') USA = ConcreteColleague('美國',mediator) mediator.colleague1 = USA Iraq = ConcreteColleague('伊拉克',mediator) mediator.colleague2 = Iraq USA.Send('不準研製核武器,否則要發動戰爭') Iraq.Send('我們沒有核武器,也不怕侵略') returnif __name__ == '__main__': clientUI();
類圖: