探索 NestJS 的依赖注入系统引发了对依赖反转、控制反转和依赖注入的更深入研究。 这些概念虽然看似相似,但却为不同的问题提供了不同的解决方案。 此解释可作为个人复习,并希望能为其他处理这些术语的人提供有用的指南。
-
依赖倒置原则(DIP)
定义:高层模块不应该依赖于低层模块;两者都应该依赖于抽象。抽象不应该依赖于细节;细节应该取决于抽象。
这意味着什么:
在软件中,高层模块封装核心业务逻辑,而低层模块处理特定的实现(数据库、API 等)。 如果没有 DIP,高层模块直接依赖低层模块,造成紧密耦合,阻碍灵活性,使测试和维护复杂化,并且使替换或扩展低层细节变得困难。
DIP 颠倒了这种关系。高层和低层模块都依赖于共享抽象(接口或抽象类),而不是直接控制。
无 DIP
Python 示例
class EmailService: def send_email(self, message): print(f"Sending email: {message}") class Notification: def __init__(self): self.email_service = EmailService() def notify(self, message): self.email_service.send_email(message)
TypeScript 示例
class EmailService { sendEmail(message: string): void { console.log(`Sending email: ${message}`); } } class Notification { private emailService: EmailService; constructor() { this.emailService = new EmailService(); } notify(message: string): void { this.emailService.sendEmail(message); } }
问题:
- 紧密耦合:
Notification
直接依赖于EmailService
。 - 扩展性有限:切换到
SMSService
需要修改Notification
。
含浸
Python 示例
from abc import ABC, abstractmethod class MessageService(ABC): @abstractmethod def send_message(self, message): pass class EmailService(MessageService): def send_message(self, message): print(f"Sending email: {message}") class Notification: def __init__(self, message_service: MessageService): self.message_service = message_service def notify(self, message): self.message_service.send_message(message) # Usage email_service = EmailService() notification = Notification(email_service) notification.notify("Hello, Dependency Inversion!")
TypeScript 示例
interface MessageService { sendMessage(message: string): void; } class EmailService implements MessageService { sendMessage(message: string): void { console.log(`Sending email: ${message}`); } } class Notification { private messageService: MessageService; constructor(messageService: MessageService) { this.messageService = messageService; } notify(message: string): void { this.messageService.sendMessage(message); } } // Usage const emailService = new EmailService(); const notification = new Notification(emailService); notification.notify("Hello, Dependency Inversion!");
DIP 的好处:
- 灵活性:轻松交换实现。
- 可测试性:使用模拟进行测试。
- 可维护性:低级模块的更改不会影响高级模块。
-
控制反转 (IoC)
IoC 是一种设计原则,其中依赖控制转移到外部系统(框架)而不是在类内进行管理。 传统上,类创建并管理其依赖项。 IoC 逆转了这一点——外部实体注入依赖项。
Python 示例:没有 IoC
class SMSService: def send_message(self, message): print(f"Sending SMS: {message}") class Notification: def __init__(self): self.sms_service = SMSService() # Dependency created internally def notify(self, message): self.sms_service.send_message(message)
TypeScript 示例:没有 IoC
class SMSService { sendMessage(message: string): void { console.log(`Sending SMS: ${message}`); } } class Notification { private smsService: SMSService; constructor() { this.smsService = new SMSService(); // Dependency created internally } notify(message: string): void { this.smsService.sendMessage(message); } }
没有 IoC 的问题:
- 紧密耦合。
- 灵活性低。
- 困难的测试。
Python 示例:使用 IoC
class EmailService: def send_email(self, message): print(f"Sending email: {message}") class Notification: def __init__(self): self.email_service = EmailService() def notify(self, message): self.email_service.send_email(message)
TypeScript 示例:使用 IoC
class EmailService { sendEmail(message: string): void { console.log(`Sending email: ${message}`); } } class Notification { private emailService: EmailService; constructor() { this.emailService = new EmailService(); } notify(message: string): void { this.emailService.sendEmail(message); } }
国际奥委会的好处:
- 松散耦合。
- 轻松实现切换。
- 提高了可测试性。
-
依赖注入 (DI)
DI 是一种对象从外部源接收其依赖项的技术。 这是 IoC 的实际实现,通过以下方式注入依赖项:
- 构造函数注入
- 二传手注射
- 接口注入
Python 示例:DI 框架(使用 injector
库)
from abc import ABC, abstractmethod class MessageService(ABC): @abstractmethod def send_message(self, message): pass class EmailService(MessageService): def send_message(self, message): print(f"Sending email: {message}") class Notification: def __init__(self, message_service: MessageService): self.message_service = message_service def notify(self, message): self.message_service.send_message(message) # Usage email_service = EmailService() notification = Notification(email_service) notification.notify("Hello, Dependency Inversion!")
TypeScript 示例:DI 框架(使用 tsyringe
库)
interface MessageService { sendMessage(message: string): void; } class EmailService implements MessageService { sendMessage(message: string): void { console.log(`Sending email: ${message}`); } } class Notification { private messageService: MessageService; constructor(messageService: MessageService) { this.messageService = messageService; } notify(message: string): void { this.messageService.sendMessage(message); } } // Usage const emailService = new EmailService(); const notification = new Notification(emailService); notification.notify("Hello, Dependency Inversion!");
DI 的好处:
- 简化测试。
- 提高了可扩展性。
- 增强的可维护性。
这个详细的解释阐明了 DIP、IoC 和 DI 之间的关系和区别,强调了它们对构建健壮且可维护的软件的个人贡献。
以上是分解依赖倒置、IoC 和 DI的详细内容。更多信息请关注PHP中文网其他相关文章!

Linux终端中查看Python版本时遇到权限问题的解决方法当你在Linux终端中尝试查看Python的版本时,输入python...

本文解释了如何使用美丽的汤库来解析html。 它详细介绍了常见方法,例如find(),find_all(),select()和get_text(),以用于数据提取,处理不同的HTML结构和错误以及替代方案(SEL)

Python的statistics模块提供强大的数据统计分析功能,帮助我们快速理解数据整体特征,例如生物统计学和商业分析等领域。无需逐个查看数据点,只需查看均值或方差等统计量,即可发现原始数据中可能被忽略的趋势和特征,并更轻松、有效地比较大型数据集。 本教程将介绍如何计算平均值和衡量数据集的离散程度。除非另有说明,本模块中的所有函数都支持使用mean()函数计算平均值,而非简单的求和平均。 也可使用浮点数。 import random import statistics from fracti

本文比较了Tensorflow和Pytorch的深度学习。 它详细介绍了所涉及的步骤:数据准备,模型构建,培训,评估和部署。 框架之间的关键差异,特别是关于计算刻度的

本文讨论了诸如Numpy,Pandas,Matplotlib,Scikit-Learn,Tensorflow,Tensorflow,Django,Blask和请求等流行的Python库,并详细介绍了它们在科学计算,数据分析,可视化,机器学习,网络开发和H中的用途

本文指导Python开发人员构建命令行界面(CLIS)。 它使用Typer,Click和ArgParse等库详细介绍,强调输入/输出处理,并促进用户友好的设计模式,以提高CLI可用性。

在使用Python的pandas库时,如何在两个结构不同的DataFrame之间进行整列复制是一个常见的问题。假设我们有两个Dat...

文章讨论了虚拟环境在Python中的作用,重点是管理项目依赖性并避免冲突。它详细介绍了他们在改善项目管理和减少依赖问题方面的创建,激活和利益。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境