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?
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.
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With