spring - 基于参数的函数解析器?

时间:2013-02-11 16:50:03

标签: java spring

我在基于弹簧配置的示例之后,根据参数的值,调用不同的函数。

我一直在谷歌搜索“弹簧功能解析器”或类似的东西,但唉,我似乎无法在网上找到任何东西。

基本上,所有函数都会以某种方式存储在某个地方,并根据此参数的值调用不同的函数。

例如“PameterISA” - >调用A()

“ParameterISB” - >调用B()

等...

这可以通过Spring轻松完成吗?

由于

1 个答案:

答案 0 :(得分:0)

如果PameterISAPameterISB可以是实现公共接口的不同类的实例,则面向对象的处理方式可以使用strategy pattern

interface Strategy {
    void doIt();
}

class ClassA implements Strategy {
    @Override
    public void doIt() {
        // execute the code that corresponds to A()
    }
}

class ClassB implements Strategy {
    @Override
    public void doIt() {
        // execute the code that corresponds to B()
    }
}

现在,你所要做的就是

Strategy PameterISA = new ClassA();
Strategy PameterISB = new ClassB();

// ...

Strategy strategy = // an instance of either ClassA or ClassB
strategy.doIt();    // will call the correct method.

或者,如果参数是byteshortchar int(或其盒装对应物),enum或(从Java 7开始) )String,您可以使用普通的switch语句:

switch (parameter) {
    case "PameterISA":
        A();
        break;
    case "PameterISB":
        B();
        break;
    default:
        throw new IllegalArgumentException(parameter);
}

最后,您可以使用程序if - else if - else模式。