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

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

问题描述

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

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 的工作方式相同,但 Strategy 用于更细粒度和短期的依赖项.

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

当对象配置了固定"策略时,例如在构造对象时,策略和 DI 之间的区别变得模糊.但在 DI 场景中,对象的依赖关系在其生命周期内发生变化的情况更为罕见,而这在 Strategy 中并不少见.

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 中使用的接口只有一个实现是很常见的.只有一个具体实现(曾经)的策略"并不是真正的问题,但可能更接近于 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天全站免登陆