Design Patterns : Chain of Responsibility


Object-oriented developers strive to keep object loosely coupled, keeping the responsibility between objects specific and minimal.. This leads to introduce a change easily with less risk of defects. Clients see only an object’s visible interface and remain isolated from the details of the object’s implementation.



Avoid coupling the sender of a request to its receiver by giving more than one object the chance to handle the request. To apply this pattern, chain the receiving objects and pass the request along the chain until an object handles it.



Use Chain of Responsibility pattern when

  • There are more than one handler that can handle a request and there is no way to know which handler to use, but the handler must be determined automatically by the chain.
  • There is a need to issue a request to one of several objects without specifying which one explicitly.
  • There is a need to able to modify the set of objects dynamically that can handle requests.




Code Sample

import java.util.*;
abstract class Logger {
    public static int ERR = 3;
    public static int NOTICE = 5;
    public static int DEBUG = 7;
    protected int mask;
    // The next element in the chain of responsibility
    protected Logger next;
    public Logger setNext( Logger l)    {
        next = l;
        return l;
    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( "Sending via email: " + msg );
class StderrLogger extends Logger {
    public StderrLogger( int mask ) { this.mask = mask; }
    protected void writeMessage( String msg )    {
        System.err.println( "Sending to stderr: " + msg );
public class ChainOfResponsibilityExample {
    public static void main( String[] args )     {
        // Build the chain of responsibility
        Logger l,l1;
        l1 = l = new StdoutLogger( Logger.DEBUG );
        l1 = l1.setNext(new EmailLogger( Logger.NOTICE ));
        l1 = l1.setNext(new StderrLogger( Logger.ERR ));
        // Handled by StdoutLogger
        l.message( "Entering function y.", Logger.DEBUG );
        // Handled by StdoutLogger and EmailLogger
        l.message( "Step1 completed.", Logger.NOTICE );
        // Handled by all three loggers
        l.message( "An error has occurred.", Logger.ERR );


Share this post

Related Posts