Matlab责任链模式

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

posted on 2019-05-21 16:10  sw-lab  阅读(460)  评论(0编辑  收藏  举报

导航