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

烈酒焚心 提交于 2019-12-01 09:45:17

问题


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.



来源:https://stackoverflow.com/questions/55979891/is-chain-of-responsibility-pattern-just-an-overkill-a-list-of-handlers-can-acc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!