I want to get an intuitive feeling for Chain of Responsibility pattern. I guess a good way to get that would be to learn about some real world examples. Can you guys share such examples?
One of the things about this pattern is that if the chain has many stages, lets say more than 10, implementation gets quite ugly. What do you guys do about that?
I think the Servlet filters are a good example. The chain is built for you and you can decide to call the next one. However the construction/wiring is done for you here.
If the 10 is hairy you can simplify with a builder:
interface ChainElement {
void setNext(ChainElement next);
void doSomething();
}
class ChainBuilder {
private ChainElement first;
private ChainElement current;
public ChainBuilder then(ChainElement next) {
if (current == null) {
first = current = next;
} else {
current.setNext(next);
current = next;
}
return this;
}
public ChainElement get() {
return first;
}
}
Then at construction:
ChainElement chain = new ChainBuilder()
.then(new FirstElement())
.then(new SecondElement())
.then(new ThirdElement())
.get();
chain.doSomething();