Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strategy Pattern vs Dependency Injection

How is strategy pattern is different then dependency injection?

ie below is what you can do with Strategy pattern:

class Foo{
   private readonly ISortAlgo _sortAlgo;

  public Foo(ISortAlgo sortAlgo)
  {
     _sortAlgo = sortAlgo;
  }

  public void Sort()
  {
    _sortAlgo.sort();
  }

}

with DI you can do the same, essentially you can have constructor, setter, interface etc. injection. and it would give the same effect as Strategy pattern. I am aware that DI is also set of other principles, such as loose coupling, testability, wiring etc.

In terms of implementation i dont see much difference.

what s the difference between strategy pattern and DI?

like image 546
DarthVader Avatar asked Aug 07 '12 16:08

DarthVader


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 the difference between dependency injection and factory pattern?

The real difference between factory and dependency injection lies in the fact that in the case of a factory, your dependent class is still reliant on a factory, which is a new form of dependency while DI takes out the dependency completely.

What are the three types of dependency injection?

There are three main styles of dependency injection, according to Fowler: Constructor Injection (also known as Type 3), Setter Injection (also known as Type 2), and Interface Injection (also known as Type 1).

What type of pattern is 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.


2 Answers

First, dependency injection has not only constructor injection as method to inject, but also property, method injection and ambient context.

Second, stategy defines behaviour, so client could select special one that matches on his needs. While dependency injection works with abstraction of external dependencies.

like image 75
Akim Avatar answered Sep 21 '22 14:09

Akim


The Strategy pattern allows an object's behavior (i.e. its algorithms) to be selected at runtime, where as Dependency injection allows the removal of hard-coded dependencies.

They are therefore not competitors. Their implementations might be similar, their aim, however, is different.

like image 44
Olivier Jacot-Descombes Avatar answered Sep 20 '22 14:09

Olivier Jacot-Descombes