Is Chain of Responsibility pattern just an overkil

2020-03-30 07:00发布

问题:

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.

回答1:

The chain is organized recursively just so that a handler can:

  • Do some work before the next handler runs, including modifying the input to the next handler; AND
  • Do some work after the next handler runs, including processing or modifying the output of the next handler before it is returned to the previous handler; AND
  • Use information it stored before the next handler ran to affect the output afterwards.

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.