C#设计模式:责任链模式

发表于:2017-4-10 09:52

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:刘蔡涛    来源:博客园

#
DoNet
分享:
  设计模式是面向对象编程的基础,是用于指导程序设计。在实际项目开发过程中,并不是一味将设计模式进行套用,也不是功能设计时大量引入设计模式。应该根据具体需求和要求应用适合的设计模式。设计模式是一个老话题了,因为最近在设计“网关API”组件(后续介绍),采用“责任链设计模式”进行设计,所以先进行回顾记录
  一、责任链模式介绍
  责任链模式是指一个处理需要涉及多个过程或者角色参与处理,并基于某个约定组成一个链,每个过程或者角色拥有各自职责进行处理。责任链模式有效组织一个过程处理,同时子过程之间职责明确。在.NET平台中很常见此模式应用。例如管道方式就可以采用责任链模式进行设计实现。
  二、责任链模式结构图
  如下图所示,此类图就是责任链模式核心的结构图,常见定义一个接口各子过程基础此接口实现,通过接口进行解耦子过程之间依赖。
  三、责任链模式实现
  通过如下简单DEMO进行展示责任链的实现。定义一个接口(Ihandler)、三个实现类(AHandler、BHandler、CHandler)和一个上下文类(PipelContext)。
public interface IHandler
{
PipelContext DoAction(PipelContext pipelContext);
}
public class AHandler : IHandler
{
private IHandler NextHandler { get; set; }
public AHandler(IHandler nextHandler)
{
NextHandler = nextHandler;
}
public PipelContext DoAction(PipelContext pipelContext)
{
bool isNext = (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
{
private IHandler NextHandler { get; set; }
public BHandler(IHandler nextHandler)
{
NextHandler = nextHandler;
}
public PipelContext DoAction(PipelContext pipelContext)
{
bool isNext = (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
{
private IHandler NextHandler { get; set; }
public CHandler(IHandler nextHandler)
{
NextHandler = nextHandler;
}
public PipelContext DoAction(PipelContext pipelContext)
{
bool isNext = (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 void Main(string[] args)
{
IHandler ModuleC = new CHandler(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);
}
}
  四、总结
  上述只是一个很简单的责任链模式,实际应用中根据需求,子过程可以采用可配置方式实现热插拔式,提升灵活、扩展及可维护。
100家互联网大公司java笔试题汇总,填问卷领取~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号