今天来聊聊设计模式中的中介者模式
中介者模式(Mediator pattern):
中介者对象:封装所有互连,作为通信枢纽,负责控制和协调其客户的交互,并通过保持对象明确地引用彼此来促进松耦合。
python 代码:(来源)
"""
Define an object that encapsulates how a set of objects interact.
Mediator promotes loose coupling by keeping objects from referring to
each other explicitly, and it lets you vary their interaction
independently.
"""
class Mediator:
"""
Implement cooperative behavior by coordinating Colleague objects.
Know and maintains its colleagues.
"""
def __init__(self):
self._colleague_1 = Colleague1(self)
self._colleague_2 = Colleague2(self)
class Colleague1:
"""
Know its Mediator object.
Communicate with its mediator whenever it would have otherwise
communicated with another colleague.
"""
def __init__(self, mediator):
self._mediator = mediator
class Colleague2:
"""
Know its Mediator object.
Communicate with its mediator whenever it would have otherwise
communicated with another colleague.
"""
def __init__(self, mediator):
self._mediator = mediator
def main():
mediator = Mediator()
if __name__ == "__main__":
main()
总结:
中介者模式(Mediator Pattern)是用来降低多个对象和类之间的通信复杂性。这种模式提供了一个中介类,该类通常处理不同类之间的通信,并支持松耦合,使代码易于维护。
参考链接:
(1)https://sourcemaking.com/design_patterns/mediator(顺便提高英文阅读理解能力)
(2)http://www.runoob.com/design-pattern/mediator-pattern.html(比较简单易懂)