责任链模式

定义

  /// <summary>
  /// 定义处理接口
  /// </summary>
  public interface IHandler
  {
      public IHandler? next { get; set; }
      void Response();
  }

  /// <summary>
  /// 定义处理类
  /// </summary>
  public class HandlerBase : IHandler
  {
      public IHandler? next { get; set; }
      private Action? BeginAction { get; set; }
      private Action? EndAction { get; set; }
      private Action DoAction { get; set; }

      /// <summary>
      /// 构造函数
      /// </summary>
      /// <param name="doAction">处理逻辑</param>
      /// <param name="startAction">处理前</param>
      /// <param name="endAction">处理后</param>
      public HandlerBase(Action doAction, Action? beginAction, Action? endAction)
      {
          DoAction = doAction;
          BeginAction = beginAction;
          EndAction = endAction;
      }

      /// <summary>
      /// 开始执行
      /// </summary>
      public void Response()
      {
          //开始处理前
          this.BeginAction?.Invoke();
          //处理中
          this.DoAction.Invoke();
          //调用下一处理节点
          this.next?.Response();
          //处理后
          this.EndAction?.Invoke();
      }
  }

调用

Console.WriteLine("责任链模式");
HandlerBase handlerOne = new HandlerBase(
    () => { Console.WriteLine("程序1处理中"); },
    () => { Console.WriteLine("程序1开始处理"); },
    () => { Console.WriteLine("程序1结束处理"); }
    );
HandlerBase handlerTwo = new HandlerBase(
       () => { Console.WriteLine("程序2处理中"); },
    () => { Console.WriteLine("程序2开始处理"); },
    () => { Console.WriteLine("程序2结束处理"); }
    );
HandlerBase handlerThree = new HandlerBase(
       () => { Console.WriteLine("程序3处理中"); },
    () => { Console.WriteLine("程序3开始处理"); },
    () => { Console.WriteLine("程序3结束处理"); }
    );
handlerOne.next = handlerTwo;
handlerTwo.next = handlerThree;
handlerOne.Response();

 

输出

 

总结

责任链模式执行过程类似于一个U型结构,在dotnetcore中消息管道中间件的处理就用到了责任链的设计模式

 

posted @ 2024-04-01 15:07  DaiWK  阅读(3)  评论(0编辑  收藏  举报