Skip to content

Instantly share code, notes, and snippets.

@slmanju
Last active February 14, 2018 03:55
Show Gist options
  • Select an option

  • Save slmanju/4644714a0e8d6082a7dc0133df500d40 to your computer and use it in GitHub Desktop.

Select an option

Save slmanju/4644714a0e8d6082a7dc0133df500d40 to your computer and use it in GitHub Desktop.
Chain of responsibility demonstration
public abstract class Chain {
protected Chain next;
public Chain() {
}
public void setNext(Chain next) {
this.next = next;
}
public abstract void execute(Request request);
}
public class ChainA extends Chain {
@Override
public void execute(Request request) {
// any logic related to this class
if (Request.Type.A.equals(request.getType())) {
System.out.println("doing the task in condition A");
} else {
next.execute(request); // or else delegate to next chain
}
}
}
public class ChainB extends Chain {
@Override
public void execute(Request request) {
// any logic related to this class
if (Request.Type.B.equals(request.getType())) {
System.out.println("doing the task in condition B");
} else {
next.execute(request); // or else delegate to next chain
}
}
}
public class ChainC extends Chain {
@Override
public void execute(Request request) {
// any logic related to this class
if (Request.Type.C.equals(request.getType())) {
System.out.println("doing the task in condition C");
} else {
// last in the chain
System.out.println("no one to handle your request");
}
}
}
public class CorDemo {
public static void main(String[] main) {
Chain chain = createChain();
Request request = new Request(Request.Type.A);
System.out.println(">>>> A");
chain.execute(request);
System.out.println(">>>> C");
request.setType(Request.Type.C);
chain.execute(request);
}
// it is important to build the chain correctly.
private static Chain createChain() {
Chain chainC = new ChainC();
Chain chainB = new ChainB();
Chain chainA = new ChainA();
chainA.setNext(chainB);
chainB.setNext(chainC);
return chainA;
}
}
public class Request {
private Type type;
public Request(Type type) {
this.type = type;
}
public void setType(Type type) {
this.type = type;
}
public Type getType() {
return type;
}
enum Type {
A, B, C
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment