战略模式与依赖注入有什么区别? [英] What is the difference between Strategy pattern and Dependency Injection?

查看:102
本文介绍了战略模式与依赖注入有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

策略模式和依赖注入两者都允许我们在运行时设置/注入对象。策略模式和依赖注入有什么区别?

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?

推荐答案

DI和Strategy的工作方式相同,但策略用于更细粒度和短期的依赖关系。

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

当对象配置有固定策略时,例如,当对象构建时,策略和 DI模糊。但是,在DI方案中,对象的依赖关系在其生命周期内发生变化是更为不寻常的,而这在策略中并不罕见。

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.

策略侧重于意图,并鼓励您创建一个与遵循相同行为合同的不同实现的接口。 DI更多的只是实现一些行为并提供它。

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.

使用DI,您可以分解您的程序的其他原因,而不仅仅是为了交换部分实现。在DI中使用的接口只有一个实现是非常常见的。只有一个具体实施的策略(ever)并不是一个真正的问题,而是更接近于DI。

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.

这篇关于战略模式与依赖注入有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆