Cagdas Basaraner

About Cagdas Basaraner

Cagdas Basaraner is a software engineer graduated from Hacettepe University Computer Engineering department (Turkey), having 5 years professional experience. He is working on JEE web technologies, and also a former developer of information systems using Microsoft technologies and Command & Control (C4I) systems with Java technologies.

Chain of Responsibility Pattern in Java

Chain of Responsibility design pattern is needed when a few processors should exist for performing an operation and a particular order should be defined for those processors. Also the changeability of the order of processors on runtime are important.UML represantation of the pattern is as below:

Handler defines the general structure of processor objects. ‘HandleRequest’ here is the abstract processor method. Handler also has a reference of its own type, which represents the next handler. For this a public ‘setNextHandler’ method should be defined and exactly the handler is an abstract class. ConcreteHandler define different representations of processors. At last, Client is responsible with creating required handlers (processors) and define a chain order between them.
Generally two diffent implementation may exist for this pattern. Difference is related with the ‘location of the chain routing business logic’. Chain routing business logic may be either in Handler abstract class or ConcreteHandler classes, or both of them. Sample of first two approaches will be given below:

1. ‘Handler’ has chain routing business logic:

public abstract class Processor {
    protected Processor next;
    protected int threshold;
    public void setNextProcessor(Processor p) {
        next = p;
    }
    public void process(String data, int value) {
        if (value <= threshold) {
            process(data);
        }
        if (next != null) {
            next.message(data, threshold);
        }
    }
    abstract protected void processData(String data);
}
public class ProcessorA extends Processor {

    public ProcessorA (int threshold) {
        this.threshold = threshold;
    }
    protected void processData(String data) {
        System.out.println("Processing with A: " + data);
    }
}
public class ProcessorB extends Processor {

    public ProcessorB (int threshold) {
        this.threshold = threshold;
    }
    protected void writeMessage(String data) {
        System.err.println("Processing with B: " + data);
    }
}
public class Client {
    public static void main(String[] args) {
        Processor p, p1, p2;
        p1 = p = new ProcessorA(2);
        p2 = new ProcessorB(1);
        p1.setNextProcessor(p2);
        // Handled by ProcessorA
        p.process("data1", 2);
        // Handled by ProcessorA and ProcessorB
        p.process("data2", 1);
    }
}

2. ‘ConcreteHandler’s have chain routing business logic:

public abstract class Processor {
    protected Processor next;
    protected int threshold;
    public void setNextProcessor(Processor p) {
        next = p;
    }
    abstract protected void processData(String data);
}
public class ProcessorA extends Processor {

    public ProcessorA (int threshold) {
        this.threshold = threshold;
    }
    protected void processData(String data, int value) {
        System.out.println("Processing with A: " + data);
        if (value >= threshold && next != null) {
            next.processData(data, value);
        }
    }
}
public class ProcessorB extends Processor {

    public ProcessorB (int threshold) {
        this.threshold = threshold;
    }
    protected void processData(String data, int value) {
        System.out.println("Processing with B: " + data);
        if (value >= threshold && next != null) {
            next.processData(data, value);
        }
    }
}
public class Client {
    public static void main(String[] args) {
        Processor p, p1, p2;
        p1 = p = new ProcessorA(2);
        p2 = new ProcessorB(1);
        p1.setNextProcessor(p2);
        // Handled by ProcessorA
        p.processData("data1", 1);
        // Handled by ProcessorA and ProcessorB
        p.processData("data2", 2);
    }
}

Reference: 2 Implementations of “Chain of Responsibility” Pattern with Java from our JCG partner Cagdas Basaraner at the CodeBuild blog.

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

One Response to "Chain of Responsibility Pattern in Java"

  1. Basil Abbas says:

    The code has many problems, a call to message(..) in Processer exists, however, the method is not defined in the code. I think the coder meant to call process(..) instead.

Leave a Reply


2 − = one



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books