责任链模式仅仅是一个过大的杀伤力吗?处理程序列表可以完成相同的操作 [英] Is Chain of Responsibility pattern just an overkill ? A List of Handlers can accomplish the same

查看:70
本文介绍了责任链模式仅仅是一个过大的杀伤力吗?处理程序列表可以完成相同的操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在责任链(COR)模式中,我们创建了一系列处理程序。将请求传递到链中的第一个。它试图处理它。如果不能,则将请求转发到链中的下一个,依此类推。
例如Handler1 =新的ConcreteHandler1();
handler1.handle

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. 对于for循环,这比COR低吗?

  2. 是否存在for循环更好和COR更好的情况?
    在您的回答中-如果您在进行详细说明之前先用是/否回答这些问题,那就太好了。

我知道已经有关于此的帖子-责任链与类列表相比有什么优势?但它并不能澄清我的疑问。

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:


  • 做一些工作在下一个处理程序运行之前,包括修改对下一个处理程序的输入; AND

  • 在下一个处理程序运行之后 做一些工作,包括在下一个处理程序返回到前一个处理程序之前对其进行处理或修改; AND

  • 使用下一个处理程序运行之前存储的信息来影响之后的输出。

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

当处理程序不产生任何输出(如HTML事件处理程序)时,两者都必须先完成工作之后就没有必要了。在这种情况下,通常会按照您的建议反复调用事件处理程序。

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.

这篇关于责任链模式仅仅是一个过大的杀伤力吗?处理程序列表可以完成相同的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆