design-patternschain-of-responsibility

Is Chain of Responsibility pattern just an overkill ? A List of Handlers can accomplish the same


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.

  1. In what way is this for loop inferior to COR? Is n't COR just an overkill?
  2. 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.


Solution

  • 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.