What would you like to correct and/or improve in this java implementation of Chain Of Responsibility
- by Maciek Kreft
package design.pattern.behavioral;
import design.pattern.behavioral.ChainOfResponsibility.*;
public class ChainOfResponsibility {
public static class Chain {
private Request[] requests = null;
private Handler[] handlers = null;
public Chain(Handler[] handlers, Request[] requests){
this.handlers = handlers;
this.requests = requests;
}
public void start() {
for(Request r : requests)
for (Handler h : handlers)
if(h.handle(r)) break;
}
}
public static class Request {
private int value;
public Request setValue(int value){
this.value = value;
return this;
}
public int getValue() {
return value;
}
}
public static class Handler<T1> {
private Lambda<T1> lambda = null;
private Lambda<T1> command = null;
public Handler(Lambda<T1> condition, Lambda<T1> command) {
this.lambda = condition;
this.command = command;
}
public boolean handle(T1 request) {
if (lambda.lambda(request))
command.lambda(request);
return lambda.lambda(request);
}
}
public static abstract class Lambda<T1>{
public abstract Boolean lambda(T1 request);
}
}
class TestChainOfResponsibility {
public static void main(String[] args) {
new TestChainOfResponsibility().test();
}
private void test() {
new Chain(new Handler[]{ // chain of responsibility
new Handler<Request>(
new Lambda<Request>(){ // command
public Boolean lambda(Request condition) {
return condition.getValue() >= 600;
}
},
new Lambda<Request>(){
public Boolean lambda(Request command) {
System.out.println("You are rich: " + command.getValue() + " (id: " + command.hashCode() + ")");
return true;
}
}
),
new Handler<Request>(
new Lambda<Request>(){
public Boolean lambda(Request condition) {
return condition.getValue() >= 100;
}
},
new Lambda<Request>(){
public Boolean lambda(Request command) {
System.out.println("You are poor: " + command.getValue() + " (id: " + command.hashCode() + ")");
return true;
}
}
),
},
new Request[]{
new Request().setValue(600), // chaining method
new Request().setValue(100),
}
).start();
}
}