Chain Of Responsibility Pattern In Java

Chain Of Responsibility Pattern

Overview: A method called in one class will move up a class hierarchy until a method is found that can properly handle the call.It consists of a source of command objects and a series of processing objects.Each processing object contains a set of logic that describes the types of command objects that it can handle,and how to pass off those that it cannot to the next processing object in the chain.A mechanism also exists to add new processing objects in the chain.

Intent:Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request.Chain the receiving objects and pass the request along the chain until an object handles it.There is potentially variable number of “handler” objects and a stream of requests that must be handled.

also read:

Discussion:The pattern chains the receiving objects together,and then passes any request messages from object to object until it reaches an object capable of handling the message.

Chain of responsibility simplifies object interconnections.Instead of senders and receivers maintaining references to all candidate receivers,each sender keeps a single reference to the head of the chain,and each receiver keeps a single reference to the immediate successor in the chain.

We need to make sure to catch any requests go unhandled.

Do not use Chain of Responsibility when each request is handled by one handler,or,when the client knowns which service object should handle the request.

Example: The Chain of Responsibility pattern avoids coupling the sender of a request to the receiver,by giving more than one object a chance to handle the request.Mechanical coin sorting banks use the Chain of Responsibility.Rather than having a seperate slot for each coin denomination coupled with a receptacle for the denomination,a single slot is used.When the coin is dropped,the coin is routed to the appropriate receptacle by the mechanical mechanisms within the bank.

Rules Of Thumb: Chain of Responsibility,Command Pattern,Mediator Pattern and Observer Pattern address how you can decouple senders and receivers,but diff trade-offs.Chain of Responsibility passes a request along with a chain of potential receivers.

Chain Of Responsibility uses Command Pattern to represent requests as objects.[GoF,p349]

Chain of Responsibility is often applied in conjunction with CompositePattern.There,a component’s parent act as its successor.[Gof,p232]

Note that each node along the chain of responsibility must be able to either directly handle or forward the request.If the “request” is coded directly as,for instance,a c++ method call,then every node along the chain must define that method call,with non-handling nodes merely re-invoking the method on the parent.To avoid having each node define methods for all possible requests,in a static language like c++,require that a command pattern be used,where an actual object encapsulates the request.Note however that using a command object to pass around requests on the chain of responsibility is less efficient than using the language’s built in command mechanism.

If request’s don’t need to follow long chains of responsibility,a better pattern to use is mediator so that only mediator node needs to know about all possible requests coming from its child nodes,and these methods could be coded in native language methods,affording clarity and speed.

Is it not that “non-resumptive exception handling” in mordern object oriented languages like c++ and java,follow ChainOfResponsibilityPattern pattern? When can exception is thrown,the exception handlers are looked up for a match.The exception object is passed till a matching handler is found.So,can it be assumed that exception handling follows ChainOfResponsibilityPattern?

People confuse whether class Inheritance in ObjectOrientedLanguage such as Java,SmallTalk a more common application of this pattern? When a method is called on an object,the method dispatch system tries to find the method on the object being called,then on it’s parent etc on up the tree.

But it it not totally true.Inheritance functions more like a message broker.The runtime locates a function to call and calls it.Chain of Responsibility functions more like a message bus.Each receiving object is given a chance to handle the message or pass it along.Inheritance can be made to function in this way by using “base” or “super” calls.but it is not as natural a fit as seperate handler classes and it constraints the inheritance tree – DavidSidlinger?

Below example gives one implementation of COR.

package year2008;

abstract class Logger {

 public static int ERR=3;
 public static int NOTICE=5;
 public static int DEBUG=7;
 public int mask;

 // The Next Element in the Chain of Responsibility
 protected Logger next;

 protected Logger setNext(Logger l) {
  next=l;
  return this;
 }

 public void message(String msg,int priority) {
  if(priority<=mask)
   writeMessage(msg);
  if(next!=null)
   next.message(msg,priority);
 }


 abstract protected void writeMessage(String msg);
}

class StdoutLogger extends Logger {

 public StdoutLogger(int mask) { this.mask=mask; }

 protected void writeMessage(String msg) {
  System.out.println("Writing to stdout:" + msg);
 }
}

class EmailLogger extends Logger {

 public EmailLogger(int mask) { this.mask=mask; }

 protected void writeMessage(String msg) {
  System.out.println("Writing to email:" + msg);
   }
}

public class ChainOfResponsibilityExample {
 public static void main(String[] args) {
  Logger l=new StdoutLogger(Logger.DEBUG).setNext(new EmailLogger(Logger.NOTICE));
  l.message("Entering function",Logger.DEBUG);
  // Handled by StdoutLogger and EmailLogger
        l.message( "Step1 completed.", Logger.NOTICE );

   }
}

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*