Hello,
I found out an interesting and useful implementation of Chain of responsibility pattern and would like to share it.:
On Classical implementation, each concrete handler is responsible of it's own successor object (the ring which comes from itself) as well. This creates a dependency problem and unnecessarry complexity..
For classical implementation look: http://www.oodesign.com/chain-of-responsibility-pattern.html
This implementation has a recursive structure and it triggers a chain reaction with calling the first ring of the chain.
public abstract class GroupChain {
private GroupChain next;
public void setNext(GroupChain nextG) {
next = nextG;
}
public final Integer start(int value) {
Integer result = this.execute(value);
if (next != null) {
Integer nextResult = next.start(value);
if (nextResult != null)
result += (nextResult);
}
return result;
}
protected abstract Integer execute(int value);
}
public class FirstChain extends GroupChain {
@Override
protected Integer execute(int value) {
return value * 2;
}
}
public class SecondChain extends GroupChain{
@Override
protected Integer execute(int value) {
return value * 5;
}
}
public class ThirdChain extends GroupChain {
@Override
protected Integer execute(int value) {
return value * 2;
}
}
public class Orchestrator {
public static void main(String[] args) {
FirstChain firstChain = new FirstChain();
SecondChain secondChain = new SecondChain();
ThirdChain thirdChain = new ThirdChain();
firstChain.setNext(secondChain);
secondChain.setNext(thirdChain);
System.out.println(firstChain.start(3));
}
}
Hiç yorum yok:
Yorum Gönder