Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is dependency injection just another name for the strategy pattern? [duplicate]

Strategy pattern and Dependency Injection both allow us to set / inject objects at run time. What is the difference between Strategy pattern and Dependency Injection?

like image 878
Nero Avatar asked Nov 14 '10 06:11

Nero


People also ask

Is dependency injection a strategy pattern?

Dependency injection is a refinement of the strategy pattern which I will briefly explain. It is often necessary to choose between several alternative modules at runtime. These modules all implement a common interface so that they can be used interchangeably.

What is meant by dependency injection?

In software engineering, dependency injection is a design pattern in which an object or function receives other objects or functions that it depends on. A form of inversion of control, dependency injection aims to separate the concerns of constructing objects and using them, leading to loosely coupled programs.

What is the alternative to dependency injection?

An alternative to dependency injection is using a service locator. The service locator design pattern also improves decoupling of classes from concrete dependencies. You create a class known as the service locator that creates and stores dependencies and then provides those dependencies on demand.


1 Answers

DI and Strategy work in the same way, but Strategy is used for more fine-grained and short-lived dependencies.

When an object is configured with a "fixed" Strategy, for example when the object is constructed, the distinction between Strategy and DI blurs. But in a DI scenario it is more unusual that the dependencies of objects change during their lifetimes, while this is not uncommon with Strategy.

Also, you can pass strategies as arguments to methods, while the related concept of method argument injection is not widespread and mostly used in the context of automated testing only.

Strategy focuses on intent and encourages you to create an interface with different implementations that obey the same behavioral contract. DI is more about just having an implementation of some behavior and providing it.

With DI you can decompose your program for other reasons than just to be able to swap parts of the implementation. An interface used in DI with only one implementation is very common. A "Strategy" with only one concrete implementation (ever) is not a real problem but is probably closer to DI.

like image 143
eljenso Avatar answered Oct 11 '22 06:10

eljenso