我在基于弹簧配置的示例之后,根据参数的值,调用不同的函数。
我一直在谷歌搜索“弹簧功能解析器”或类似的东西,但唉,我似乎无法在网上找到任何东西。
基本上,所有函数都会以某种方式存储在某个地方,并根据此参数的值调用不同的函数。
例如“PameterISA” - >调用A()
“ParameterISB” - >调用B()
等...
这可以通过Spring轻松完成吗?
由于
答案 0 :(得分:0)
如果PameterISA
和PameterISB
可以是实现公共接口的不同类的实例,则面向对象的处理方式可以使用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.
或者,如果参数是byte
,short
,char
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
模式。