Say I\'m using spring, I have the following strategies...
Interface
public interface MealStrategy {
cook(Meat meat);
}
First st
I would use simple Dependency Injection.
@Component("burger")
public class BurgerStrategy implements MealStrategy { ... }
@Component("sausage")
public class SausageStrategy implements MealStrategy { ... }
Controller
Option A:
@Resource(name = "burger")
MealStrategy burger;
@Resource(name = "sausage")
MealStrategy sausage;
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody Something makeMeal(Meat meat) {
burger.cookMeal(meat);
}
Option B:
@Autowired
BeanFactory bf;
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody Something makeMeal(Meat meat) {
bf.getBean("burger", MealStrategy.class).cookMeal(meat);
}
You can choose to create JSR-330 qualifiers instead of textual names to catch misspellings during compile time.
See also:
How to efficiently implement a strategy pattern with spring?
@Resource vs @Autowired
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<String, MealStrategy> mealStrategies = new HashMap<>;
@RequestMapping(method=RequestMethod.POST)
public @ResponseBody Something makeMeal(@RequestParam(value="mealStrategyId") String mealStrategyId, Meat meat) {
mealStrategies.get(mealStrategyId).cook(meat);
...
}