设计模式是面向对象编程的基础,是用于指导程序设计。在实际项目开发过程中,并不是一味将设计模式进行套用,也不是功能设计时大量引入设计模式。应该根据具体需求和要求应用适合的设计模式。设计模式是一个老话题了,因为最近在设计 "网关 API" 组件(后续介绍),采用 "责任链设计模式" 进行设计,所以先进行回顾记录。
一、责任链模式介绍
责任链模式是指一个处理需要涉及多个过程或者角色参与处理,并基于某个约定组成一个链,每个过程或者角色拥有各自职责进行处理。责任链模式有效组织一个过程处理,同时子过程之间职责明确。在. NET 平台中很常见此模式应用。例如管道方式就可以采用责任链模式进行设计实现。
二、责任链模式结构图
如下图所示,此类图就是责任链模式核心的结构图,常见定义一个接口各子过程基础此接口实现,通过接口进行解耦子过程之间依赖。
三、责任链模式实现
通过如下简单 DEMO 进行展示责任链的实现。定义一个接口(Ihandler)、三个实现类(AHandler、BHandler、CHandler)和一个上下文类(PipelContext)。
- public interface IHandler
- {
- PipelContext DoAction(PipelContext pipelContext);
- }
- public class AHandler : IHandler
- {
- privateIHandler NextHandler {get;set; }
- public AHandler(IHandler nextHandler)
- {
- NextHandler = nextHandler;
- }
- public PipelContext DoAction(PipelContext pipelContext)
- {
- boolisNext = (pipelContext.Flag <20)true:false;
- pipelContext.request ="AA";
- Console.WriteLine("my is "+ pipelContext.request);
- if(NextHandler !=null&& isNext)
- {
- NextHandler.DoAction(pipelContext);
- }
- return pipelContext;
- }
- }
- public class BHandler : IHandler
- {
- privateIHandler NextHandler {get;set; }
- public BHandler(IHandler nextHandler)
- {
- NextHandler = nextHandler;
- }
- public PipelContext DoAction(PipelContext pipelContext)
- {
- boolisNext = (pipelContext.Flag <10)true:false;
- pipelContext.request ="BB";
- Console.WriteLine("my is "+ pipelContext.request);
- if(NextHandler !=null&& isNext)
- {
- NextHandler.DoAction(pipelContext);
- }
- return pipelContext;
- }
- }
- public class CHandler : IHandler
- {
- privateIHandler NextHandler {get;set; }
- public CHandler(IHandler nextHandler)
- {
- NextHandler = nextHandler;
- }
- public PipelContext DoAction(PipelContext pipelContext)
- {
- boolisNext = (pipelContext.Flag <5)true:false;
- pipelContext.request ="CC";
- Console.WriteLine("my is "+ pipelContext.request);
- if(NextHandler !=null&& isNext)
- {
- NextHandler.DoAction(pipelContext);
- }
- return pipelContext;
- }
- }
- public class PipelContext {
- public PipelContext() {
- Key = Guid.NewGuid();
- }
- public Guid Key {
- get;
- set;
- }
- public int Flag {
- get;
- set;
- }
- public string request {
- get;
- set;
- }
- public string respone {
- get;
- set;
- }
- }
- static voidMain(string[] args)
- {
- IHandler ModuleC =newCHandler(null);
- IHandler ModuleB =new BHandler(ModuleC);
- IHandler ModuleA =new AHandler(ModuleB);
- PipelContext p =new PipelContext();
- while(true)
- {
- p.Flag = Convert.ToInt32(Console.ReadLine());
- ModuleA.DoAction(p);
- }
- }
四、总结
上述只是一个很简单的责任链模式,实际应用中根据需求,子过程可以采用可配置方式实现热插拔式,提升灵活、扩展及可维护。
来源: http://www.cnblogs.com/Andon_liu/p/6685218.html