Design Patterns – Difference Between Strategy Pattern and Dependency Injection

design-patterns

I was reading "Beginning Spring" and this particular paragraph caught my attention:

The DI pattern resembles other patterns such as Factory or Strategy.
We can say that with the Factory pattern the instantiation of objects
is still within the responsibility of the Factory definition, which
is your code, but with the DI it’s externalized to another
component/framework. On the other hand, with the Strategy pattern, the
current implementation gets replaced with the help of multiple objects
of a same interface, which contain that implementation inside.
However, with the DI, the objects that contain those implementations
are wired regardless of the implementation defined.

I am not sure if I understand what the author is saying in the emphasised part, but reading this made me realise, Strategy Pattern is an Inversion of Control implementation, isn 't it? (Q1)

So my second question (Q2) is: How is Strategy Pattern different compared to Dependency Injection?

Best Answer

The strategy pattern, simply put, is providing the ability to specify a concrete behavior for something so that its consumer can ignore what the concrete behavior is. An example is something like a logging strategy. The thing doing the logging doesn't care where the log messages go.

Dependency Injection is the idea that things are given their dependencies rather than seeking them out.

There's still scenarios where code would know how to build the strategy they want, or otherwise directly depend on the strategy implementations. They're uncommon and best avoided, but hopefully that helps distinguish the orthogonal concepts for you.