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. MRP-MD04 中的函数

    1.需求溯源 : MD_PEGGING_NODIALOG 2.实时库存 : MD_STOCK_REQUIREMENTS_LIST_API 这个函数中MDPSX 和 MDEZX 是通过 MDPS 的 I ...

  2. C++使用模板、函数指针、接口和lambda表达式这四种方法做回调函数的区别比较

    在C++中,两个类之间存在一种关系,某个类需要另外一个类去完成某一个功能,完成了之后需要告知该类结果,这种最普通最常见的需求,往往使用回调函数来解决. 如题,我总结下来有这么四种方式可以完成这项功能, ...

  3. VC实现趋势图绘制

    本文参考pudn上一个完整工程,在pudn搜索“50815867CurveDrawing”即可找到源代码.   上图是使用VS2010重写了该软件后的效果图,下面再贴出关键代码: // Plot.cp ...

  4. swt_table 回车可编辑Esc取消

    package 宿舍管理系统; import java.util.Hashtable; import org.eclipse.swt.SWT; import org.eclipse.swt.custo ...

  5. NEU 1681: The Singles

    题目描述 The Signals’ Day has passed for a few days. Numerous sales promotion campaigns on the shopping ...

  6. ADB结构及代码分析【转】

    本文转载自:http://blog.csdn.net/happylifer/article/details/7682563 最近因为需要,看了下adb的源代码,感觉这个作者很牛,设计的很好,于是稍微做 ...

  7. Uboot中start.S源码的指令级的详尽解析【转】

    本文转载自:http://www.crifan.com/files/doc/docbook/uboot_starts_analysis/release/html/uboot_starts_analys ...

  8. leelazero and google colab

    https://github.com/gcp/leela-zero/blob/master/COLAB.md 左侧菜单展开,可以查看细节

  9. DedeCMS模板中用彩色tag做彩色关键词

    DedeCMS模板中用彩色tag做彩色关键词,下面分享一下吧!修改方法: 1.在/include/common.func.php 中加入如下函数: function getTagStyle() { $ ...

  10. 获取cookies的简单代码(总结待续)

    Cookie[] cookies = request.getCookies(); Cookie cookie = null; for (int i = 0; i < cookies.length ...