您的位置:首页 > 大数据 > 人工智能

The Chain Of Responsibility Pattern

2013-11-26 19:38 260 查看



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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息