简体   繁体   English

用Spring实现Factory方法

[英]Implement Factory method with Spring

What would be the best way to implement a factory method using Spring? 使用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 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. 您正在混淆工厂方法和spring应用程序上下文。

What you should do is creating 2 beans in the application context one called cheeseService and the other one called veggieService. 您应该做的是在应用程序上下文中创建2个bean,一个叫做CheeseService,另一个叫做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. 之后,您应该只创建一个静态方法getService,该方法将根据spring应用程序上下文中的PizzaType返回bean之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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