Search code examples
design-patternsinversion-of-controlstrategy-pattern

Can anyone explain how the Strategy Pattern relates to Inversion of Control?


Can anyone explain exactly how the Strategy Pattern relates to Inversion of Control?


Solution

  • When you use the strategy pattern, you want your other classes to depend on the interface rather than a concrete strategy. One way to do this is to have the concrete strategy injected into a class that uses it as the interface rather than having the class understand how to create the appropriate strategy. This is where IoC/Dependency Injection comes in.

    The idea would be that you have some sort of configuration or decision class that defines which strategies to use. This could be an IoC framework, but it doesn't necessarily have to be. This class is responsible for configuring your other classes with the appropriate strategy based on system state or configuration. The concrete strategy is created and injected via a constructor or property settor and thus "control" over which strategy class is instantiated is "inverted" -- it is not done by the class depending on it but, rather, from outside.