它不是这样工作的——如果你有一个特定的Util实现,比如说,连接到类SampleClass(它是一个单例),你不能在不重新启动应用程序上下文的情况下,将Util的实现真正更改为不同的实现.
因此,我建议另一种 Select ,而不是走这条路.您说,在运行时判断的特定条件下,您希望切换实现.这是什么情况?是否可以提取该条件决策逻辑?
如果是这样,您可以自动连接一个特殊的DynamicUtil,它将保存对所有util的引用,并根据条件调用所需的util:
// represents all possible business 'runtime' outcomes
enum ConditionOutcome {
A, B, C
}
interface ConditionEvaluator {
ConditionOutcome evaluate(); // when called in runtime will evaluate a condition that currently exists in the system
}
interface Util {
void foo();
ConditionOutcome relevantOfOutcome();
}
class Utill1Impl implements Util {
public void foo() {...}
public ConditionOutcome relevantOfOutcome() {return ConditionOutcome.A;}
}
class Utill2Impl implements Util {
public void foo() {...}
public ConditionOutcome relevantOfOutcome() {return ConditionOutcome.B;}
}
class Utill3Impl implements Util {
public void foo() {...}
public ConditionOutcome relevantOfOutcome() {return ConditionOutcome.C;}
}
class DynamicUtil {
private final Map<ConditionOutcome, Util> possibleImpls;
private final ConditionEvaluator evaluator;
public class DynamicUtil(List<Util> allImplementations, ConditionEvaluator evaluator) {
// create a map by calling the 'relevantOfOutcome' per util impl in a loop
this.evaluator = evaluator;
}
public void foo() {
ConditionOutcome key = evaluator.evaluate();
// pick the relevant implementation based on evaluated key
possibleImpls.get(key).foo();
}
}
现在有了这样的设计,您可以动态地添加新的可能结果(以及应该实现它们的UTIL).不过,系统中的类将必须自动连接DynamicUtil
,因此有效地引入了一个额外的间接级别,但将获得灵活性
class SampleClass { // a business class that will need to work with util capable of being changed during the runtime
@Autowired
private DynamicUtil util;
...
}