Strategy pattern with spring beans

后端 未结 2 1732
灰色年华
灰色年华 2020-12-04 10:00

Say I\'m using spring, I have the following strategies...

Interface

public interface MealStrategy {
    cook(Meat meat);
}

First st

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 10:38

    Since a concrete strategy is very often determined at run time based on the provided parameters or so, I would suggest something as follows.

    @Component
    public class BurgerStrategy implements MealStrategy { ... }
    
    @Component
    public class SausageStrategy implements MealStrategy { ... }
    

    Then inject all such strategies into a map (with bean name as a key) in the given controller and select respective strategy on request.

    @Autowired
    Map mealStrategies = new HashMap<>;
    
    @RequestMapping(method=RequestMethod.POST)
    public @ResponseBody Something makeMeal(@RequestParam(value="mealStrategyId") String mealStrategyId, Meat meat) {
        mealStrategies.get(mealStrategyId).cook(meat);
    
        ...
    }
    

提交回复
热议问题