【发布时间】:2012-10-30 07:33:36
【问题描述】:
我有以下代码:
public IFoo getFoo(Type type) // Type is an enum containing A, B etc.
{
switch(type)
{
case A: return new Foo1(); // implements IFoo
case B: return new Foo2(); // implements IFoo
etc.
}
}
这显然违反了OCP,所以我需要重构;另外,我现在需要返回由 Spring 容器管理的原型 bean。为此,我可以考虑以下选项:
1) 使此类 AppContextAware;创建一个 Map
2) 类似的方法,但对于 Map 中的值,使用具有抽象方法的 TargetSource,我在 getTarget() 中调用该方法,并使用 lookup-method 作为每个 TargetSource 定义的抽象方法连接定义的原型 bean,
3) 类似的方法,但我使用 FactoryBean 而不是 TargetSource。
在 #1 中,我的课程依赖于 AppContext,而在其他方法中则不依赖。所以我倾向于#2 或#3,但是选择哪一个呢?或者有没有其他更好的方法我没有想到?
【问题讨论】: