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.
- In what way is this for loop inferior to COR? Is n't COR just an overkill?
- Are there scenarios where this for loop is better and others where COR is better? In your answer - it will be great if you can first answer these questions with Yes/No before going into the detailed explanation.
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.