Chain of Responsibility Code in Java
Chain.java: This is the interface that acts as a chain link.
package com.java.behavioral.chainofresponsibility;
public interface Chain {
public abstract void setNext(Chain nextInChain);
public abstract void process(Number request);
}
Number.java: This class represents the request object.
package com.java.behavioral.chainofresponsibility;
public class Number {
private int number;
public Number(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
}
NegativeProcessor.java: This class acts as the link in the chain series.
package com.java.behavioral.chainofresponsibility;
public class NegativeProcessor implements Chain {
private Chain nextInChain;
public void setNext(Chain c) {
nextInChain = c;
}
public void process(Number request) {
if(request.getNumber() < 0) {
System.out.println("NegativeProcessor : " + request.getNumber());
} else {
nextInChain.process(request);
}
}
}
ZeroProcessor.java: This class is another link in the chain series.
package com.java.behavioral.chainofresponsibility;
public class ZeroProcessor implements Chain {
private Chain nextInChain;
public void setNext(Chain c) {
nextInChain = c;
}
public void process(Number request) {
if (request.getNumber() == 0) {
System.out.println("ZeroProcessor : " + request.getNumber());
} else{
nextInChain.process(request);
}
}
}
PositiveProcessor.java:
This class represents another link in the chain series.
package com.java.behavioral.chainofresponsibility;
public class PositiveProcessor implements Chain {
private Chain nextInChain;
public void setNext(Chain c) {
nextInChain = c;
}
public void process(Number request) {
if(request.getNumber() > 0) {
System.out.println("PositiveProcessor : " + request.getNumber());
}else {
nextInChain.process(request);
}
}
}
TestChain.java:
This class configures the chain of responsibility and executes it.
package com.java.behavioral.chainofresponsibility;
public class TestChain {
public static void main(String[] args) {
//configure Chain of Responsibility
Chain c1 = new NegativeProcessor();
Chain c2 = new ZeroProcessor();
Chain c3 = new PositiveProcessor();
c1.setNext(c2);
c2.setNext(c3);
//calling chain of responsibility
c1.process(new Number(99));
c1.process(new Number(-30));
c1.process(new Number(0));
c1.process(new Number(100));
}
}