打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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    endend

 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    endend

 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    endend

 测试代码:

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.");
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
设计模式之责任链模式
大数据Scala系列之特质
ios UIWebView通过javascript调用本地api
Android API Level对应Android版本一览表
显示实现接口
学习lumberjack framework(中文版)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服