我为什么要对转换陈述使用责任链 [英] Why would I use a chain of responsibility over a switch-statement

查看:86
本文介绍了我为什么要对转换陈述使用责任链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑您进行了几次验证。仅当要检查的对象属于某种类型时,这些验证才应生效。为什么我要对转换陈述使用责任链?

Consider you got several validations. Those validations should only take effect if the object to be inspected is of a certain type. Why would I use a chain of responsibility over a switch-statement?

责任链示例

public class Executor {

@Inject
private ValidatorFactory validatorFactory;

public void execute(Konfiguration konfig) {
    List<Statement> statements = konfig.getStatements();
    AbstractValidator validator = validatorFactory.create();
    for (Statement statement : statements) {
        if (validator.validate(statement.getType())) {
            crudService.execute(statement.getSql());
        }
    }
}

validatorFactory创建以下项的链验证者。一个验证器看起来像

The validatorFactory creates the chain of Validators. One validator would look like

public class AddPrimaryKeyValidator extends AbstractValidator {

@Override
public boolean validate(Statement statement) {
    if (SqlType.ADD_PK.getTyp().equals(statement.getType())) {
        return doesTableAndPrimaryKeyExist(statement.getTabName());
    }
    return successor.validate(statement);
}

带有切换语句的示例

public void execute(Konfiguration konfig) {
    List<Statement> statements = konfig.getStatements();
    for (Statement statement : statements) {
        switch (statement.getType()) {
        case "ADD_PK":
            if (doesTableAndPrimaryKeyExist(statement.getTabName())) {
                frepCrudService.execute(statement.getSql());
            }
            // more cases
        }
    }
}


推荐答案

由于在责任链中,您不需要知道谁在呼叫者中先做了什么。决定何时在链中运行代码的逻辑由您所有,其余代码可以忽略它。这样可以将特定的逻辑封装在正确的位置。 Servlet过滤器就是一个很好的例子

Because in a chain of responsibility you don't need to know who does what up front in the caller. The logic of decide when you are about to run your piece of code in a chain is owned by you and the rest of the code can ignore it. This allow to encapsulate specific logic in the right place. Servlet filters are a good example of this

这篇关于我为什么要对转换陈述使用责任链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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