职责什么是责任链模式中 吗

从真实项目中抠出来的设计模式——第三篇:责任链模式
一:现实场景
有时候在开发的过程中,我们经常会根据某个状态的值,写出很多的ifelse逻辑,比如拿项目里面的案例来说,如果当前发送的是彩信,此种状态需要如何给实体赋值,如果是短信,邮件又是其他方式的赋值,等等此类,这种情况下一般会写出如下if判断,对吧,真实代码如下:
if (municationtypeEnum.HasFlag(CommunicationTypeEnum.邮件))
//第三步:动态生成邮件模板
var styleInfo = CacheUtil.GetRandomEmailStyle();
var tuple = new EdmDraftBoxBLL().GetEdmHtmlTitle(communicationInfo.EDMJson, styleInfo.StyleId);
leaflet.Title = tuple.Item1;
leaflet.EDMContent = tuple.Item2;
leaflet.Header = tuple.Item3;
leaflet.SendSMSCount = 1;
if (municationtypeEnum.HasFlag(CommunicationTypeEnum.短信))
leaflet.SMSContent = communicationInfo.SMSC
leaflet.SendSMSCount = communicationInfo.SMSC
if (municationtypeEnum.HasFlag(CommunicationTypeEnum.彩信))
leaflet.MMSContent = communicationInfo.MMSC
上面的代码还是非常简单明了的,程序会根据municationtypeEnum的不同做不同的判断,比如说当前状态是邮件的话,程序会从30套邮件
模板库中随机抽取一封,给leaflet的title,header...赋值,有些人可能会说这段代码不难看哈,确实是这样,但是如果面对需求变更呢?比如说后期需要增加微信,微博渠道,那是不是又要加上两个if才能把这个问题解决呢? 这就违背了设计模式中开闭原则,对吧,面对这种场景,可以用责任链模式摆平。
二:责任链模式
责任链模式讲的就是将请求的发送者和接收者进行分离,避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止,面对需求变更,只需要更加处理类就好了,而且客户端可以按照自己的需求拼接处理链条,是不是很强大。
1. AbstractComunication
public abstract class AbstractComunication
AbstractComunication abstractComunication =
public void SetHandler(AbstractComunication abstractComunication)
this.abstractComunication = abstractC
public abstract void HanderRequest(LeafletEntity leaflet,
EventmarketingSmsEdmContentInfo communicationInfo);
2. MMSComunication
public class MMSComunication : AbstractComunication
public override void HanderRequest(LeafletEntity leaflet, EventmarketingSmsEdmContentInfo communicationInfo)
if (municationtypeEnum.HasFlag(CommunicationTypeEnum.彩信))
leaflet.MMSContent = communicationInfo.MMSC
abstractComunication.HanderRequest(leaflet, communicationInfo);
3.EDMComunication
public class EDMComunication : AbstractComunication
public override void HanderRequest(LeafletEntity leaflet, EventmarketingSmsEdmContentInfo communicationInfo)
if (municationtypeEnum.HasFlag(CommunicationTypeEnum.邮件))
//第三步:动态生成邮件模板
var styleInfo = CacheUtil.GetRandomEmailStyle();
var tuple = new EdmDraftBoxBLL().GetEdmHtmlTitle(communicationInfo.EDMJson, styleInfo.StyleId);
leaflet.Title = tuple.Item1;
leaflet.EDMContent = tuple.Item2;
leaflet.Header = tuple.Item3;
leaflet.SendSMSCount = 1;
abstractComunication.HanderRequest(leaflet, communicationInfo);
4.SMSComunication
public class SMSComunication : AbstractComunication
public override void HanderRequest(LeafletEntity leaflet, EventmarketingSmsEdmContentInfo communicationInfo)
if (municationtypeEnum.HasFlag(CommunicationTypeEnum.短信))
leaflet.SMSContent = communicationInfo.SMSC
leaflet.SendSMSCount = communicationInfo.SMSC
abstractComunication.HanderRequest(leaflet, communicationInfo);
5.客户端调用
AbstractComunication communication1 = new EDMComunication();
AbstractComunication communication2 = new SMSComunication();
AbstractComunication communication3 = new MMSComunication();
//手工将三个Comunication 凭借成一个链条,形成单链表的模型
communication1.SetHandler(communication2);
communication2.SetHandler(communication3);
communication1.HanderRequest(leaflet, communicationInfo);
其实上面的代码,需要绕一下脑子的就是如何通过SetHandler将三个xxxComunication拼接成一个单链表的形式,链表怎么拼接在于客户端如何设置sethandler,
灵活性完全就在客户端这边,然后就非常方便将leaflet在责任链中游走,最终会被某一状态处理逻辑处理,讲到这里,我想大家应该都知道责任链模式是干嘛的了,
由于是真实案例就不方便跑代码了,下面我构建一个责任链模型,大家比照一下就可以了,是不是有种请求和处理的分离,而且我还可以根据需要组合我的责任链,
其实js的冒泡机制就是这种模式的一个体现。
public abstract class AbstractHandler
protected AbstractHandler abstractHandler =
public void SetHandler(AbstractHandler abstractHandler)
this.abstractHandler = abstractH
public virtual void HandleRequest(int request) { }
public class ConcreteHandler1 : AbstractHandler
public override void HandleRequest(int request)
if (request == 1)
Console.WriteLine("handler1 给你处理了");
abstractHandler.HandleRequest(request);
public class ConcreteHandler2 : AbstractHandler
public override void HandleRequest(int request)
if (request == 2)
Console.WriteLine("handler2 给你处理了");
abstractHandler.HandleRequest(request);
public class ConcreteHandler3 : AbstractHandler
public override void HandleRequest(int request)
if (request == 3)
Console.WriteLine("handler3 给你处理了");
abstractHandler.HandleRequest(request);
class Program
static void Main(string[] args)
AbstractHandler hander1 = new ConcreteHandler1();
AbstractHandler hander2 = new ConcreteHandler2();
AbstractHandler hander3 = new ConcreteHandler3();
hander1.SetHandler(hander2);
hander2.SetHandler(hander3);
hander1.HandleRequest(3);
好了,模板和实际项目的案例都给大家展示了,希望能帮助到你
原文地址:/huangxincheng/p/6429284.html
责任编辑:
声明:本文由入驻搜狐号的作者撰写,除搜狐官方账号外,观点仅代表作者本人,不代表搜狐立场。
今日搜狐热点责任链模式一 - Java综合 - Java - ITeye论坛
责任链模式一
锁定老帖子
精华帖 (0) :: 良好帖 (0) :: 新手帖 (1) :: 隐藏帖 (1)
来自: 兰州
发表时间:&&
相关知识库:
责任链模式(Chain of Responsibility)是Web项目中最经常用到的一个设计模式,比如是Apache Tomcat 的对Encoding的 处理,Struts2 的拦截器, jsp servlet 的Filter 等等,都是基于责任链模式设计的。比如有一个作业任务,先有一个对象对其负责处理,之后又交给其他的一个对象处理,一次传递下去,这是最通俗最简单的责任链模式的应用。但是责任链模式不仅仅的的就局限于这一种的最简单的应用,比如通信领域的短信验证码的获取,请求验证码----&发送验证码-----& 处理验证码-----&提交验证码-----&得到结果 等等的应用都和责任链模式密布可分。不一定非要在设计中就是用设计模式,但是联系联系周围的环境,思考思考周边的应用,自然的规律的轮回,都都感觉和设计模式有瓜葛。
现在就模拟对网站信息处理的字符处理展示下什么是责任链模式:
需要准备一下几个类:
Filter :处理过滤信息的过滤接口类
* @author Bestupon
* @EMail :
* 处理过滤信息的过滤接口类
public interface Filter {
public String doFilter(String msg) ;
HTMLFilter负责专门过滤HTML代码的过滤器 实现了Filter 接口
package org.bestupon.pd.
* @author Bestupon
* @EMail :
* 负责专门过滤HTML代码的过滤器 实现了Filter 接口
public class HtmlFilter implements Filter {
public String doFilter(String msg) {
String result = msg.replace("&", "[").replace("&", "]");
SesitiveFilter
:负责了处理敏感词汇的过滤器 实现了Filter 接口
package org.bestupon.pd.
* @author Bestupon
* @EMail :
* 负责了处理敏感词汇的过滤器 实现了Filter 接口
public class SesitiveFilter
implements Filter{
public String doFilter(String msg) {
return msg.replaceAll("敏感", "普通词汇");
package org.bestupon.pd.
import java.util.ArrayL
import java.util.L
* @author Bestupon
* @EMail :
* 负责了处理敏感词汇的过滤器 实现了Filter 接口
* 实现Filter 接口的主要原因是:将自身也设计成一个Filter,容易构建一个chain。
public abstract class AbsractFilterChian implements Filter {
public List&Filter& filters = new ArrayList&Filter&();
public abstract String doFilter(String msg) ;
public abstract AbsractFilterChian addAbsractFilterChian(Filter filter);
package org.bestupon.pd.
* @author Bestupon
* @EMail :
* 提供处理的对外统一接口
public class MsgProcessor {
* 多个过滤器组合到一起之后就会形成过滤器链。
* 好处是过滤规则的排序,
* 先后顺序的的原因,新旧规则可以灵活的替换更新
* 责任链模式
private AbsractFilterC
public AbsractFilterChian getChian() {
public void setChian(AbsractFilterChian chian) {
this.chian =
public String getMsg() {
public void setMsg(String msg) {
this.msg =
public String process() {
return chian.doFilter(msg);
package org.bestupon.pd.
import org.apache.log4j.L
* @author Bestupon
* @EMail :
* 外部(客户端调用)
public class Main {
private static Logger log = Logger.getLogger(Main.class);
public static void main(String[] args) {
String msg = "&Script language='javascript'&javascript 代码&/script& 敏感信息";
AbsractFilterChian chian = new FilterChian();
chian.addAbsractFilterChian(new HtmlFilter());
AbsractFilterChian chian2 = new FilterChian();
chian2.addAbsractFilterChian(new SesitiveFilter());
chian.addAbsractFilterChian(chian2);
MsgProcessor processor = new MsgProcessor();
processor.setChian(chian);
processor.setMsg(msg);
("HTML结果:" + processor.process());
运行结果:16:50:37,640 INFO
[org.bestupon.pd.filter.Main] HTML结果:[Script language='javascript']javascript 代码[/script] 普通词汇信息
(653.8 KB)
下载次数: 164
等级: 初级会员
来自: 北京
发表时间:&&
貌似chian 写错了.
* chian n. 沥青,柏油.
* chain n. 链;束缚;枷锁.
请登录后投票
抛出异常的爱
文章: 13675
积分: 2762
来自: 北京
发表时间:&&
楼主再好好想个例子吧.....这个例子用错了.
请登录后投票
来自: 兰州
发表时间:&&
weather 写道/**
貌似chian 写错了.
* chian n. 沥青,柏油.
* chain n. 链;束缚;枷锁.
*/
的确写错了!应该是chain!
请登录后投票
climber2002
来自: 法国
发表时间:&&
异常说得没错,你这个例子确实用错了,servlet的Filter是责任链模式,但你这个不是,你这个充其量算是Composite模式而已.
请登录后投票
climber2002
来自: 法国
发表时间:&&
引用比如通信领域的短信验证码的获取,请求验证码----&发送验证码-----& 处理验证码-----&提交验证码-----&得到结果 等等的应用都和责任链模式密布可分。
我第一直觉是用State模式
请登录后投票
跳转论坛:移动开发技术
Web前端技术
Java企业应用
编程语言技术1、职责链模式简介
1.1&、定义
  职责链模式是一种行为模式,为解除请求的发送者和接收者之间的耦合,而使多个对象都有机会处理这个请求。将这些对象连接成一条链,并沿着这条链传递该请求,直到有一个对象处理它。
1.2&、使用频率
2、职责链模式结构
2.1&、结构图
2.2&、参与者
  职责链模式参与者:
  & Handler
    & 定义一个处理请求的接口
    & 实现后继链
  & ConcreteHandler
    & 处理其所负责的请求
    & 可访问其后继者
    & 如果可处理该请求,则处理;否则将该请求转发给它的后继者。
  & Client:向链上的具体处理者对象提交请求
  在职责链模式中,Client向Handler提交请求,请求在多个ConcreteHandler对象形成的对象链中被传递,请求在传递的过程中被处理。
3、职责链模式结构实现
  Handler.cs
using System.Collections.G
using System.L
using System.T
namespace DesignPatterns.ChainOfResponsibilityPattern.Structural
public abstract class Handler
protected H
public void SetSuccessor(Handler successor)
this.successor =
public abstract void HandleRequest(int request);
  ConcreteHandler1.cs
using System.Collections.G
using System.L
using System.T
namespace DesignPatterns.ChainOfResponsibilityPattern.Structural
public class ConcreteHandler1 : Handler
public override void HandleRequest(int request)
if (request &= 0 && request & 10)
Console.WriteLine("{0} handled request {1}", this.GetType().Name, request);
else if (successor != null)
successor.HandleRequest(request);
  ConcreteHandler2.cs
using System.Collections.G
using System.L
using System.T
namespace DesignPatterns.ChainOfResponsibilityPattern.Structural
public class ConcreteHandler2 : Handler
public override void HandleRequest(int request)
if (request &= 10 && request & 20)
Console.WriteLine("{0} handled request {1}", this.GetType().Name, request);
else if (successor != null)
successor.HandleRequest(request);
  ConcreteHandler3.cs
using System.Collections.G
using System.L
using System.T
namespace DesignPatterns.ChainOfResponsibilityPattern.Structural
public class ConcreteHandler3 : Handler
public override void HandleRequest(int request)
if (request &= 20 && request & 30)
Console.WriteLine("{0} handled request {1}", this.GetType().Name, request);
else if (successor != null)
successor.HandleRequest(request);
  Program.cs
using System.Collections.G
using System.L
using System.T
using DesignPatterns.ChainOfResponsibilityPattern.S
namespace DesignPatterns.ChainOfResponsibilityPattern
class Program
static void Main(string[] args)
// Setup Chain of Responsibility
Handler h1 = new ConcreteHandler1();
Handler h2 = new ConcreteHandler2();
Handler h3 = new ConcreteHandler3();
h1.SetSuccessor(h2);
h2.SetSuccessor(h3);
// Generate and process request
int[] requests = { 2, 5, 14, 22, 18, 3, 27, 20 };
foreach (int request in requests)
h1.HandleRequest(request);
  运行输出:
ConcreteHandler1 handled request 2
ConcreteHandler1 handled request 5
ConcreteHandler2 handled request 14
ConcreteHandler3 handled request 22
ConcreteHandler2 handled request 18
ConcreteHandler1 handled request 3
ConcreteHandler3 handled request 27
ConcreteHandler3 handled request 20
请按任意键继续. . .
  上例中,ConcreteHandler1负责处理的请求范围0~10,ConcreteHandler2负责处理的请求范围10~20,ConcreteHandler3负责处理的请求范围20~30。当请求ConcreteHandler1处理不了,则让ConcreteHandler2处理,如果ConcreteHandler2处理不了,则让ConcreteHandler3处理。依次类推,Client的请求会验证职责链传递下去,直至请求被处理,而Client不要关心到底是谁处理了请求。
4、职责链模式应用分析
  职责链模式适用情形:
  1&、可能处理请求的对象集合以及它们在链表中的顺序是由Client根据当前应用的状态在运行时动态决定的;
  2&、Client根据状态,对于不同的请求类型,可以拥有不同的可能处理请求的对象集合。一个处理请求的对象也可以根据Client的状态和请求类型,把请求传递给不同的处理对象。
  3&、Client初始化请求,或者在不知道这些对象是否能处理这个请求的情况下初始化任何可能处理请求的对象。Client和在处理链表中的处理对象都不需要知道到底哪个对象去处理这个请求。
  4&、请求不能保证被处理。在没有处理的情况下,请求已经到达了处理链的表尾。
  职责链模式特点:
  1&、职责链模式降低了发出命令的对象和处理命令的对象之间的耦合,它允许多于一个的处理者对象根据自己的逻辑来决定哪个处理者最终处理这个命令。发出命令的对象只是把命令传给链结构的起始者,而不需要知道到底是链上的哪一个节点处理了这个命令。这样在处理命令上,允许系统由更多的灵活性。哪一个对象最终处理一个命令可以由那些对象参加职责链,以及随着这些对象在职责链上的位置不同而不同。
  2&、既然一个请求没有明确的接收者,那么就不能保证它一定会被处理。该请求可能一直到链的末端都得不到处理。一个请求也可以因该链没有被正确配置而得不到响应,并且处理消息传递和处理不当会出现消息的循环重复执行。
阅读(...) 评论()第1章 什么是责任链模式
第2章 有求必应的销售队伍:怎样实现责任链模式
第3章 剖析责任链模式
第4章 责任链模式的实际应用
Copyright (C)
All Rights Reserved | 京ICP备 号-2责任链模式,chain of responsibility pattern,音标,读音,翻译,英文例句,英语词典
说明:双击或选中下面任意单词,将显示该词的音标、读音、翻译等;选中中文或多个词,将显示翻译。
您的位置: ->
-> 责任链模式
1)&&chain of responsibility pattern
责任链模式
The chain of responsibility pattern let these object which can handle the request of customer become to a chain,and a handler of the responsibility chain handles the request of a customer or deliver the request of a customer to next handler of the chain of responsibility.
责任链模式将处理用户请求的对象形成一个链,责任链上的每个处理者要么处理用户的请求,要么把请求传递给责任链上的下一个处理者。
2)&&Responsibility Model
From political,constitutional and governmental responsibility we can understand the responsibility model under the frame of traditional public administration.
政治—行政二分法和官僚制理论是传统公共行政的主要理论基础,我们可以从政治责任、宪法(法律)责任和政府整体责任几个方面来理解传统公共行政框架下的责任模式。
3)&&chain of responsibility
4)&&models of liability attribution
责任追究模式
5)&&pattern of government obligation
政府责任模式
The transmutation of the pattern of government obligation in Western countries has undergone three stages: traditional public administration, new public administration and new public management whose successful experience of obligation pattern can serve as an example for the obligation construction .
西方政府责任模式演变经历了传统公共行政、新公共行政和新公共管理的政府责任模式三个阶段。
6)&&legal liability mode
法律责任模式
补充资料:植物命名的模式和模式标本
&&& 科或科级以下的分类群的名称,都是由命名模式来决定的。但更高等级(科级以上)分类群的名称,只有当其名称是基于属名的也是 由命名模式来决定的。种或种级以下的分类群的命名必须有模式标本根据。模式标本必须要永久保存,不能是活植物。模式标本有下列几种:&&& (1)主模式标本(全模式标本、正模式标本)(holotype)是由命名人指定的模式标本,即著者发表新分类群时据以命名、描述和绘图的那一份标本。&&& (2)等模式标本(同号模式标本、复模式标本)(isotype)系与主模式标本同为一采集者在同一地点与时间所采集的同号复份标本。&&& (3)合模式标本(等值模式标本)(syntype)著者在发表一分类群时未曾指定主模式而引证了2个以上的标本或被著者指定为模式的标本,其数目在2个以上时,此等标本中的任何1份,均可称为合模式标本。&&& (4)后选模式标本(选定模式标本)(lectotype)当发表新分类群时,著作未曾指定主模式标本或主模式已遗失或损坏时,是后来的作者根据原始资料,在等模式或依次从合模式、副模式、新模式和原产地模式标本中,选定1份作为命名模式的标本,即为后选模式标本。&&& (5)副模式标本(同举模式标本)(paratype)对于某一分类群,著者在原描述中除主模式、等模式或合模式标本以外同时引证的标本,称为副模式标本。&&& (6)新模式标本(neotype)当主模式、等模式、合模式、副模式标本均有错误、损坏或遗失时,根据原始资料从其他标本中重新选定出来充当命名模式的标本。&&& (7)原产地模式标本(topotype)当不能获得某种植物的模式标本时,便从该植物的模式标本产地采到同种植物的标本,与原始资料核对,完全符合者以代替模式标本,称为原产地模式标本。
说明:补充资料仅用于学习参考,请勿用于其它任何用途。}

我要回帖

更多关于 什么是责任链模式 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信