设计模式系列 - 责任链模式

责任链模式通过为请求创建一个 接收者对象的链,对请求的发送者和接收者进行解耦。

介绍#

责任链属于行为型模式,在这种模式中,通常每个接收者都包含对另一个接收者的引用,如果一个对象不能处理该请求,那么则会继续往下传递,依此类推。可以参考 C# 中的事件处理程序就是采用这种思想。

类图描述#

代码实现#

1、创建抽象的记录器类

public abstract class AbstractLogger
{
    public static int INFO = 1;
    public static int DEBUG = 2;
    public static int ERROR = 3;

    protected int level;

    protected AbstractLogger nextLogger;

    public void SetNextLogger(AbstractLogger nextLogger)
    {
        this.nextLogger = nextLogger;
    }

    public void LogMessage(int level, string message)
    {
        if (this.level <= level)
        {
            write(message);
        }

        if (this.nextLogger != null)
        {
            nextLogger.LogMessage(level, message);
        }

    }

    protected abstract void write(string message);
}

2、创建扩展了该记录器类的实体类

public class ConsoleLogger:AbstractLogger
{
    public ConsoleLogger(int level)
    {
        this.level = level;
    }
    protected override void write(string message) => Console.WriteLine($"Standard Console::Logger{message}");
}

public class ErrorLogger:AbstractLogger
{
    public ErrorLogger(int level)
    {
        this.level = level;
    }
    protected override void write(string message) => Console.WriteLine($"Error Console::Logger:{message}");
}

public class FileLogger:AbstractLogger
{
    public FileLogger(int level)
    {
        this.level = level;
    }

    protected override void write(string message) => Console.WriteLine($"File::Logger:{message}");
}

3、上层调用

class Program
{
    private static AbstractLogger GetChainLoggers()
    {
        AbstractLogger errorLogger = new ErrorLogger(AbstractLogger.ERROR);
        AbstractLogger fileLogger = new FileLogger(AbstractLogger.DEBUG);
        AbstractLogger consoleLogger = new ConsoleLogger(AbstractLogger.INFO);

        errorLogger.SetNextLogger(fileLogger);
        fileLogger.SetNextLogger(consoleLogger);

        return errorLogger;
    }

    static void Main(string[] args)
    {
        var loggerChain = GetChainLoggers();

        loggerChain.LogMessage(AbstractLogger.INFO, "This is an information");
        loggerChain.LogMessage(AbstractLogger.DEBUG, "This is an debug level information");
        loggerChain.LogMessage(AbstractLogger.ERROR, "This is an error information");

        Console.ReadKey();
    }
}

总结#

责任链模式多在事件传递中有实际运用,通过链式结构将多个处理类关联起来,简化了上层调用,但是需要注意的是避免出现循环调用。

作者:hippiezhou

出处:https://www.cnblogs.com/hippieZhou/p/10055183.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

Find Anyway

posted @   hippieZhou  阅读(465)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu