In the 'Chain of Responsibility(COR)' pattern, we create a chain of handlers. Pass the request to the first in the chain. It tries to handle it. If it cannot, it forwards the request to the next in the chain and so on. Eg. Handler1 = new ConcreteHandler1(); handler1.handle
public class ConcreteHandler1
public void handle() {
if(can handle)
handle the request
else
concreteHandler2.handle();
}
Can't we simply create a list of handlers and accomplish the same in a for loop?
for(Handler handler : handlers) {
if(handler can handle the request)
handle
}
We will create handlers list in the same way we create the chain.
I know there is a post on this already - What are the advantages of chain-of-responsibility vs. lists of classes? but it does n't clarify my doubts.
The chain is organized recursively just so that a handler can:
Recursion is just the simplest and most straightforward way to arrange all that. To allow similar functionality without recursion would require more callbacks and a more complicated handler life cycle.
When handlers do not produce any output, like HTML event handlers, doing work both before and after is unnecessary. In these cases event handlers are usually called iteratively as you suggest.