Matlab责任链模式
程序员文章站
2022-04-30 21:02:13
责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦,本人根据https://www.runoob.com/design-pattern/chain-of-responsibility-pa ......
责任链模式(chain of responsibility pattern)为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦,本人根据https://www.runoob.com/design-pattern/chain-of-responsibility-pattern.html所给的例子,用matlab代码实现责任链模式
abstractlogger.m
classdef abstractlogger < handle & matlab.mixin.heterogeneous
properties(constant)
info = 1;
debug = 2;
error = 3;
end
properties(access = protected)
level
nextlogger = abstractlogger.empty();
end
methods(abstract,access = protected)
write(~);
end
methods
function setnextlogger(obj,nextlogger)
obj.nextlogger = nextlogger;
end
function logmessage(obj,level,message)
if(obj.level <= level)
obj.write(message);
end
if ~isempty(obj.nextlogger)
obj.nextlogger.logmessage(level, message);
end
end
end
end
consolelogger.m
classdef consolelogger < abstractlogger
methods
function obj=consolelogger(level)
obj.level = level;
end
end
methods(access = protected)
function write(~,message)
disp("standard console::logger: " + message);
end
end
end
filelogger.m
classdef filelogger < abstractlogger
methods
function obj=filelogger(level)
obj.level = level;
end
end
methods(access = protected)
function write(~,message)
disp("file console::logger: " + message);
end
end
end
errorlogger.m
classdef errorlogger < abstractlogger
methods
function obj=errorlogger(level)
obj.level = level;
end
end
methods(access = protected)
function write(~,message)
disp("error console::logger: " + message);
end
end
end
测试代码:
errorlogger = errorlogger(abstractlogger.error);
filelogger = filelogger(abstractlogger.debug);
consolelogger = consolelogger(abstractlogger.info);
errorlogger.setnextlogger(filelogger);
filelogger.setnextlogger(consolelogger);
loggerchain = errorlogger;
loggerchain.logmessage(abstractlogger.info, "this is an information.");
loggerchain.logmessage(abstractlogger.debug, "this is a debug level information.");
loggerchain.logmessage(abstractlogger.error, "this is an error information.");
下一篇: ps怎么绘制卡通动画效果的小汽车图标?