責任鏈模式(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.");