Reputation: 55132
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?
Upvotes: 16
Views: 4658
Reputation: 112782
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.
Upvotes: 13
Reputation: 15004
Dependency Injection is a pattern that help you split construction form logic which is great for testing and system extensibility. It can also be used in place where other patters fit e.g. Singleton.
Strategy pattern solves a different problem. It lets runtime to choose the algorithm - in OOP through polymorphism.
Surely, they can work together.
Upvotes: 4
Reputation: 8699
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.
Upvotes: 15
Reputation: 5503
Strategy allows you to change the behaviour of an object. DI is a design pattern that allows you to be dependent on abstractions.
Upvotes: 7