1

I have the following code:

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.
    } 
}

This obviously violates OCP, so I need to refactor; plus I now need to return prototype beans which are managed by a Spring container. To achieve this, I can think of the following options:

1) make this class AppContextAware; create a Map<Type, String> where String is the bean id; define these beans as prototype in Spring Config and define this Map too in Spring config and get it injected in this class, then get the bean id from this map for a given enum and use it to get a bean from AppContext,

2) similar approach, but for the value in Map, use a TargetSource which has an abstract method which I call in getTarget() and I wire the defined prototype beans using lookup-method as this abstract method per TargetSource definition,

3) similar approach, but I use a FactoryBean instead of TargetSource.

In #1 my class depends on AppContext, in other approaches it doesn't. So I'm leaning towards #2 or #3, but which one to pick? Or is there any other, better approach that I haven't thought of?

shrini1000
  • 7,038
  • 12
  • 59
  • 99

2 Answers2

1

I ended up using #1 anyway, as it's the simplest, and creates lesser number of beans.

shrini1000
  • 7,038
  • 12
  • 59
  • 99
0

Take a look at The FactoryBean, migth be the thing you are looking for. Take a look at here for an example.

hth

Community
  • 1
  • 1
Ortwin Angermeier
  • 5,957
  • 2
  • 34
  • 34
  • Sorry, I actually meant a FactoryBean in #3 and not BeanFactory. I've modified the question. Can you compare #2 and #3 above or suggest something else? – shrini1000 Oct 30 '12 at 10:48