public interface IMiddleware { void Invoke(PipelineContext context, Action next); } public class PipelineContext { public string Data { get; set; } } public class PipelineExecutor { private readonly List<IMiddleware> _middlewares; private int _currentIndex = 0; public PipelineExecutor() { _middlewares = new List<IMiddleware>(); } public PipelineExecutor(List<IMiddleware> middlewares) { _middlewares = middlewares; } public void Execute(PipelineContext context) { if (_currentIndex < _middlewares.Count) { var middleware = _middlewares[_currentIndex++]; middleware.Invoke(context, () => Execute(context)); } } public PipelineExecutor Use(IMiddleware middleware) { _middlewares.Add(middleware); return this; } } // 示例中间件 public class LoggingMiddleware : IMiddleware { public void Invoke(PipelineContext context, Action next) { Console.WriteLine(" Logging 开始处理请求..."); next.Invoke(); Console.WriteLine(" Logging 请求处理完毕。"); } } // 示例中间件 public class ConsoleMiddleware : IMiddleware { public void Invoke(PipelineContext context, Action next) { Console.WriteLine("Console 开始处理请求..."); next.Invoke(); Console.WriteLine("Console 请求处理完毕。"); } } //执行 var executor = new PipelineExecutor(); executor.Use(new ConsoleMiddleware()); executor.Use(new LoggingMiddleware()); var context = new PipelineContext { Data = "测试" }; executor.Execute(context);
标签:Console,Invoke,PipelineContext,中间件,管道,context,middlewares,设计模式,public From: https://www.cnblogs.com/Gekoa/p/18617474