简体   繁体   中英

Implement Factory method with Spring

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM