0

What would be the best way to implement a factory method using Spring?

@Override
public List<Prize> getPrizesForCustomer(final List<PizzaType> pizzaTypes)
{
    List<Prize> prizeList = new ArrayList<>();

    for (PizzaType type : pizzaTypes)
    {
        PizzaService prizePizzaService = PizzaFactory.getService(type);
        prizeList = prizePizzaService.populatePrizeList();
    }
}

    return prizeList;
}

MyFactory

class PizzaFactory
{
    public static PizzaService getService(final PizzaType pizza)
    {
        PizzaService pizzaService = null;

        if (pizza.equals(PizzaType.CheesePizza))
        {
            pizzaService = new CheeseServiceImpl();
        }
        else if (pizza.equals(PizzaType.Veggie))
        {
              pizzaService = new VeggieServiceImpl();
        }
        // Possibly some more pizza styles here

        return pizzaService;
     } 
}
Bartzilla
  • 2,768
  • 4
  • 28
  • 37
  • What is Spring specific there? – Rohit Jain Mar 02 '14 at 06:56
  • I could, have N amount of Implementer service (e.g. cheeseServiceImpl, veggieServiceImpl, and so on) autowired and injected. However, that seems to be odd since I will be using concrete classes. and the purpose of DI is to program to interfaces – Bartzilla Mar 02 '14 at 07:03
  • Yes, but Spring will handle that for you. The whole point of DI is that you don't use `new` operator to create instances yourself. Just register all the subclasses beans with spring container, and inject an instance based on some qualifier. – Rohit Jain Mar 02 '14 at 07:05
  • And that's the part I'm trying to figure out :) – Bartzilla Mar 02 '14 at 07:06
  • Ok, now that we're talking about Spring, can you show your beans, and the xml file showing how you're currently doing it. Forget about factories, you can do it without that too. – Rohit Jain Mar 02 '14 at 07:11
  • Ok, I have edited the question and included the client code that invokes the factory. However, in my xml I still have no beans related to the factory because I'm still not sure how to inject them. – Bartzilla Mar 02 '14 at 07:22
  • I would suggest you to please go through the [spring documentation](http://docs.spring.io/spring/docs/3.0.x/reference/beans.html#beans-factory-collaborators) to know how DI in spring works. What I see in your question is just core Java, and no spring. – Rohit Jain Mar 02 '14 at 07:27
  • It may helps you. I asked for the same information here: http://stackoverflow.com/questions/18654668/spring-servicelocator-or-pure-factory-pattern – Kakawait Mar 02 '14 at 18:56

1 Answers1

1

You are making a confusion between factory method and spring application context.

What you should do is creating 2 beans in the application context one called cheeseService and the other one called veggieService. After that you should only create a static method getService that will return one of beans depending on the PizzaType from the spring application context.

Houcem Berrayana
  • 3,052
  • 22
  • 40