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
上一篇: python 运算符 供重载参考
下一篇: PHP递归调用的小技巧讲解