Matlab中介者模式
中介者模式(Mediator Pattern)是用来降低多个对象和类之间的通信复杂性。这种模式提供了一个中介类,该类通常处理不同类之间的通信,并支持松耦合,使代码易于维护。想象一个乱糟糟的开发小组的工作状态,组员之间虽然在一起协同工作,但是意见难以统一,总是相互指挥,导致工作进度滞后。这时候,就需要一个仲裁者。所有的组员将自己的情况汇报给仲裁者,仲裁者会从团队的整体考虑,然后下达指令。仲裁者负责统一大家的意见。这样,团队的交流过程就变成了组员向仲裁者报告,仲裁者向组员下达指令的形式,而组员之间不再询问和沟通,这就是Mediator模式。
本文根据https://blog.csdn.net/niunai112/article/details/79913833所给的实例,用Matlab语言实现中介者模式
Mediator.m (抽象的中介者类)
classdef Mediator < handle properties userlist = User.empty(); end methods(Abstract) sendToAll(~,~); sendToPerson(~,~,~); join(~,~); leave(~,~); end end
ChatPlatform.m (具体的中介者类,ConcreteMediator)
classdef ChatPlatform < Mediator methods function sendToAll(obj,msg) for i=1:length(obj.userlist) obj.userlist(i).accept(msg); end end function sendToPerson(obj,name,msg) user = obj.userlist([obj.userlist.name] == name); for i = 1:length(user) user.accept(msg); end end function join(obj,user) obj.userlist(end + 1) = user; end function leave(obj,user) obj.userlist = obj.userlist(obj.userlist ~= user); end end end
User.m (抽象的同事类, Colleague)
classdef User < handle & matlab.mixin.Heterogeneous properties mediator name end methods function obj = User(name, mediator) obj.name = name; obj.mediator = mediator; end function sendToAll(obj,msg) obj.mediator.sendToAll(msg); end function sendToPerson(obj,name,msg) obj.mediator.sendToPerson(name,msg); end function join(obj) obj.mediator.join(obj); end function leave(obj) obj.mediator.leave(obj); end end methods(Abstract) accept(~,~); end end
NormalUser.m (具体的同事类, ConcreteColleague)
classdef NormalUser < User methods function obj = NormalUser(name, mediator) obj = obj@User(name, mediator); end function accept(obj,msg) disp("[" + datestr(now) + "]" + obj.name + " accepted msg: " + msg); end end end
测试代码:
chatPlatform = ChatPlatform(); a = NormalUser("A", chatPlatform); b = NormalUser("B", chatPlatform); c = NormalUser("C", chatPlatform); a.join(); b.join(); c.join(); disp("-----------------A群发送消息------------------"); a.sendToAll("A:大家听得到吗?"); disp("-----------------A给B私发消息------------------"); a.sendToPerson("B", "A:B,我只想和你说"); disp("-----------------B给A私发消息------------------"); b.sendToPerson("A","B:可以,请说" ); disp("-----------------A离开聊天室------------------"); a.leave(); disp("-----------------B群发送消息------------------"); b.sendToAll("B:A能听到吗");
参考资料
https://www.runoob.com/design-pattern/mediator-pattern.html
https://blog.csdn.net/qq_39384184/article/details/80631275
https://blog.csdn.net/niunai112/article/details/79913833