Chain of Responsibility in the Real World

The idea of the Chain Of Responsibility is that it avoids coupling the sender of the request to the receiver, giving more than one object the opportunity to handle the request.  This process of delegation appears quite frequently in the real world where there is one interface for the customer to go through. One example could be a bank, where an application that you send in to the bank branch may be handled by one particular department. Another example is a vending machine, where you can put in any coin, but the coin is passed on to the appropriate receptacle to determine the amount that the coin is worth.  

The Chain of Responsibility Pattern

The Chain of Responsibility is known as a behavioural pattern, as it's used to manage algorithms, relationships and responsibilities between objects. The definition of Chain of Responsibility provided in the original Gang of Four book on Design Patterns states: 

Gives more than one object an opportunity to handle a request by linking receiving objects together. 

Chain of Responsibility allows a number of classes to attempt to handle a request, independently of any other object along the chain. Once the request is handled, it completes it's journey through the chain.

Let's take a look at the diagram definition before we go into more detail.

The Handler defines the interface required to handle request, while the ConcreteHandlers handle requests that they are responsible for.  If the ConcreteHandler cannot handle the request, it passes the request onto it's successor, which it maintains a link to.

The objects in the chain just need to know how to forward the request to other objects.  This decoupling is a huge advantage, as you can change the chain at runtime.

Would I Use This Pattern?

This pattern is recommended when either of the following scenarios occur in your application:

  • Multiple objects can handle a request and the handler doesn't have to be a specific object
  • A set of objects should be able to handle a request with the handler determined at runtime
  • A request not being handled is an acceptable outcome.

The pattern is used in windows systems to handle events generated from the keyboard or mouse. Exception handling systems also implement this pattern, with the runtime checking if a handler is provided for the exception through the call stack. If no handler is defined, the exception will cause a crash in the program, as it is unhandled.

In JavaEE, the concept of Servlet filters implement the Chain of Responsibility pattern, and may alsodecorate the request to add extra information before the request is handled by a servlet.

So How Does It Work In Java?

Now let's take a look at how we might implement the Chain of Responsibility with a code example. Let's use an email client as an example. You might set up some rules to move a message into a particular folder depending on who it's from. First we'll need to create our EmailHandler interface.

//Handler
public interface EmailHandler
{
//reference to the next handler in the chain
public void setNext(EmailHandler handler); //handle request
public void handleRequest(Email email);
} //Now let's set up two concrete handlers, one for business mail and one for email originating from Gmail. These handlers pass on the request if it doesn't //interest them public class BusinessMailHandler implements EmailHandler
{
private EmailHandler next; public void setNext(EmailHandler handler)
{
next = handler;
} public void handleRequest(Email email)
{
if(!email.getFrom().endsWith("@businessaddress.com")
{
next.handleRequest(email);
}
else
{
//handle request (move to correct folder)
} } }
public class GMailHandler implements EmailHandler
{
private EmailHandler next; public void setNext(EmailHandler handler)
{
next = handler;
} public void handleRequest(Email email)
{
if(!email.getFrom().endsWith("@gmail.com")
{
next.handleRequest(email);
}
else
{
//handle request (move to correct folder)
} } }
//Now let's set up a client that manages the handlers - this will actually be our EmailProcessor. public class EmailProcessor
{
//maintain a reference to the previous handler so we can add the next one
private EmailHandler prevHandler; public void addHandler(EmailHandler handler)
{
if(prevHandler != null)
{
prevHandler.setNext(handler);
}
prevHandler = handler;
} }
//This class allows us to add in new handlers at any stage. Finally, the email client itself uses the EmailProcessor to look after all incoming messages //email client public class EmailClient
{
private EmailProcessor processor; public EmailClient()
{
createProcessor(); } private void createProcessor()
{
processor = new EmailProcessor();
processor.addHandler(new BusinessMailHandler());
processor.addHandler(new PersonalMailHandler());
} public void addRule(EmailHandler handler)
{
processor.addHandler(handler);
} public void emailReceived(Email email)
{
processor.handleRequest(email);
} public static void main(String[] args)
{ EmailClient client = new EmailClient(); } }

If new rules, for forwarding email to particular folders are added, we can add the handler to our email processor at runtime using the addRule() method in the client.

Watch Out for the Downsides

As with the Observer pattern, Chain of Responsibility can make it difficult to follow through the logic of a particular path in the code at runtime. It's also important to note that there is the potential that the request could reach the end of the chain and not be handled at all.

Design Patterns Uncovered: The Chain Of Responsibility Pattern的更多相关文章

  1. 深入浅出设计模式——职责链模式(Chain of Responsibility Pattern)

    模式动机 职责链可以是一条直线.一个环或者一个树形结构,最常见的职责链是直线型,即沿着一条单向的链来传递请求.链上的每一个对象都是请求处理者,职责链模式可以将请求的处理者组织成一条链,并使请求沿着链传 ...

  2. 乐在其中设计模式(C#) - 责任链模式(Chain of Responsibility Pattern)

    原文:乐在其中设计模式(C#) - 责任链模式(Chain of Responsibility Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 责任链模式(Chain of R ...

  3. 二十四种设计模式:责任链模式(Chain of Responsibility Pattern)

    责任链模式(Chain of Responsibility Pattern) 介绍为解除请求的发送者和接收者之间耦合,而使多个对象都有机会处理这个请求.将这些对象连成一条链,并沿着这条链传递该请求,直 ...

  4. C#设计模式之二十一职责链模式(Chain of Responsibility Pattern)【行为型】

    一.引言   今天我们开始讲"行为型"设计模式的第八个模式,该模式是[职责链模式],英文名称是:Chain of Responsibility Pattern.让我们看看现实生活中 ...

  5. 责任链模式 职责链模式 Chain of Responsibility Pattern 行为型 设计模式(十七)

    责任链模式(Chain of Responsibility Pattern) 职责链模式 意图 使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系 将这些对象连接成一条链,并沿着这 ...

  6. C#设计模式之二十职责链模式(Chain of Responsibility Pattern)【行为型】

    一.引言 今天我们开始讲“行为型”设计模式的第八个模式,该模式是[职责链模式],英文名称是:Chain of Responsibility Pattern.让我们看看现实生活中的例子吧,理解起来可能更 ...

  7. 19.职责链模式(Chain of Responsibility Pattern)

    19.职责链模式(Chain of Responsibility Pattern)

  8. Chain of Responsibility Pattern

    1.Chain of Responsibility模式:将可能处理一个请求的对象链接成一个链,并将请求在这个链上传递,直到有对象处理该请求(可能需要提供一个默认处理所有请求的类,例如MFC中的Cwin ...

  9. 【设计模式】行为型05责任链模式(Chain of responsibility Pattern)

    学习地址:http://www.runoob.com/design-pattern/chain-of-responsibility-pattern.html demo采用了DEBUG级别举例子,理解起 ...

随机推荐

  1. (最新)各大公司Java后端开发面试题总结

    ThreadLocal(线程变量副本) Synchronized实现内存共享,ThreadLocal为每个线程维护一个本地变量. 采用空间换时间,它用于线程间的数据隔离,为每一个使用该变量的线程提供一 ...

  2. CSS3 (二)

    translate() 方法 通过 translate() 方法,元素从其当前位置移动,根据给定的 left(x 坐标) 和 top(y 坐标) 位置参数: 示例: div { transform: ...

  3. js中!~什么意思

    (function () { var names = []; return function (name) { addName(name); } function addName(name) { if ...

  4. (linux)container_of()宏

      在学习Linux驱动的过程中,遇到一个宏叫做container_of. 该宏定义在include/linux/kernel.h中,首先来贴出它的代码: /**  * container_of - ...

  5. 织梦dedecms内页分类频道友情链接实现方法

    本文介绍了织梦dedecms中内页分类频道加友情链接的三种方法,有需要的朋友参考下. 织梦dedecms中内页分类频道加友情链接,方法有三种: 先讲方法,后讲原理: 方法:先找到首页模版index.h ...

  6. UIScrollView控件介绍

    1.UIScrollView控件是什么? (1)移动设备的屏幕⼤大⼩小是极其有限的,因此直接展⽰示在⽤用户眼前的内容也相当有限 (2)当展⽰示的内容较多,超出⼀一个屏幕时,⽤用户可通过滚动⼿手势来查看 ...

  7. Opencv:10个步骤检测出图片中条形码

    1. 原图像大小调整,提高运算效率 2. 转化为灰度图 3. 高斯平滑滤波 4.求得水平和垂直方向灰度图像的梯度差,使用Sobel算子 5.均值滤波,消除高频噪声 6.二值化 7.闭运算,填充条形码间 ...

  8. 微信小程序-B站:wxml和wxss文件

    WXML WXML(WeiXin Markup Language)是微信的一套标签语言,结合基础组件.事件系统,可以构建出页面的结构. (小安娜:好像很厉害的样子,那基础组件.事件系统是什么?感觉更厉 ...

  9. 020--python函数基础知识考试(包括:函数_递归等知识)

    1.列举布尔值为 False 的值 空,None,0, False, '', [], {}, () 2.写函数: 根据范围获取其中 3 和 7 整除的所有数的和,并返回调用者:符合条件的数字个数以及符 ...

  10. 折半插入排序 之通俗易懂,图文+代码详解-java编程

    转自http://blog.csdn.net/nzfxx/article/details/51615439 1.特点及概念介绍 下面给大家讲解一下"二分法查找"这个java基础查找 ...