Strategy Pattern vs Dependency Injection

岁酱吖の 提交于 2019-12-06 18:38:21

问题


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?


回答1:


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.




回答2:


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.




回答3:


Strategy allows you to change the behaviour of an object. DI is a design pattern that allows you to be dependent on abstractions.




回答4:


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.



来源:https://stackoverflow.com/questions/11850606/strategy-pattern-vs-dependency-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!