分解依赖倒置、IoC 和 DI
你在学习文章相关的知识吗?本文《分解依赖倒置、IoC 和 DI》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

本文深入探讨 NestJS 依赖注入系统,并阐明依赖倒置原则 (DIP)、控制反转 (IoC) 和依赖注入 (DI) 的概念及其关联。这三个概念看似相似,实则各有侧重,相互关联却又解决不同的问题。本文旨在帮助读者理清这些概念,并理解它们如何协同工作。
-
依赖倒置原则 (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或PushNotificationService需要修改Notification类。
含 DIP 示例
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)
# 使用示例
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);
}
}
// 使用示例
const emailService = new EmailService();
const notification = new Notification(emailService);
notification.notify("Hello, Dependency Inversion!");
DIP 的优势
- 灵活性:无需修改高层模块即可替换实现。
- 可测试性:使用模拟对象替换真实依赖项进行测试。
- 可维护性:低层模块的更改不会影响高层模块。
-
控制反转 (IoC)
IoC 是一种设计原则,依赖项的创建和管理由外部系统或框架控制,而不是在类内部进行。
传统编程中,类自行创建和管理依赖项。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()
def notify(self, message):
self.sms_service.send_message(message)
# 使用示例
notification = Notification()
notification.notify("Hello, tightly coupled dependencies!")
TypeScript 示例:无 IoC
class SMSService {
sendMessage(message: string): void {
console.log(`Sending SMS: ${message}`);
}
}
class Notification {
private smsService: SMSService;
constructor() {
this.smsService = new SMSService();
}
notify(message: string): void {
this.smsService.sendMessage(message);
}
}
// 使用示例
const notification = new Notification();
notification.notify("Hello, tightly coupled dependencies!");
无 IoC 的问题:
- 紧密耦合:
Notification类直接创建并依赖SMSService类。 - 灵活性低:切换到其他实现需要修改
Notification类。 - 难以测试:模拟依赖项用于单元测试比较困难,因为依赖项是硬编码的。
使用 IoC
在使用 IoC 的示例中,依赖关系的管理责任转移到外部系统或框架,实现松散耦合并增强可测试性。
Python 示例:使用 IoC
class SMSService:
def send_message(self, message):
print(f"Sending SMS: {message}")
class Notification:
def __init__(self, message_service):
self.message_service = message_service
def notify(self, message):
self.message_service.send_message(message)
# IoC: 依赖项由外部控制
sms_service = SMSService()
notification = Notification(sms_service)
notification.notify("Hello, Inversion of Control!")
TypeScript 示例:使用 IoC
class SMSService {
sendMessage(message: string): void {
console.log(`Sending SMS: ${message}`);
}
}
class Notification {
private messageService: SMSService;
constructor(messageService: SMSService) {
this.messageService = messageService;
}
notify(message: string): void {
this.messageService.sendMessage(message);
}
}
// IoC: 依赖项由外部控制
const smsService = new SMSService();
const notification = new Notification(smsService);
notification.notify("Hello, Inversion of Control!");
IoC 的优势:
- 松散耦合:类不创建其依赖项,从而减少对特定实现的依赖。
- 易于切换实现:用
EmailService替换SMSService而无需修改核心类。 - 提高可测试性:在测试期间注入模拟或 Mock 依赖项。
-
依赖注入 (DI)
DI 是一种技术,对象从外部源接收其依赖项,而不是自己创建它们。
DI 是 IoC 的一种实现方式。它允许开发人员通过多种方式将依赖项“注入”到类中:
- 构造函数注入:依赖项通过构造函数传递。
- Setter 注入:依赖项通过公共方法设置。
- 接口注入:依赖项通过接口提供。
Python 示例:使用 DI 框架
使用 injector 库:
from injector import Injector, inject
class EmailService:
def send_message(self, message):
print(f"Email sent: {message}")
class Notification:
@inject
def __init__(self, email_service: EmailService):
self.email_service = email_service
def notify(self, message):
self.email_service.send_message(message)
# DI 容器
injector = Injector()
notification = injector.get(Notification)
notification.notify("This is Dependency Injection in Python!")
TypeScript 示例:使用 DI 框架
使用 tsyringe:
import "reflect-metadata";
import { injectable, inject, container } from "tsyringe";
@injectable()
class EmailService {
sendMessage(message: string): void {
console.log(`Email sent: ${message}`);
}
}
@injectable()
class Notification {
constructor(@inject(EmailService) private emailService: EmailService) {}
notify(message: string): void {
this.emailService.sendMessage(message);
}
}
// DI 容器
const notification = container.resolve(Notification);
notification.notify("This is Dependency Injection in TypeScript!");
DI 的优势:
- 简化测试:轻松使用模拟对象替换依赖项。
- 提高可扩展性:添加新的实现而无需修改现有代码。
- 增强可维护性:减少系统某一部分变更的影响。
今天关于《分解依赖倒置、IoC 和 DI》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
解决蓝牙耳机无法连接电脑的常见问题与技巧
- 上一篇
- 解决蓝牙耳机无法连接电脑的常见问题与技巧
- 下一篇
- 我用AI帮义乌老板重新设计全红婵“丑鱼”拖鞋
-
- 文章 · python教程 | 2天前 | logging · Python教程 · 后端开发 · 日志排查 · Python logging 日志重复 propagate addHandler basicConfig
- Python logging 日志重复打印排查:为什么一条记录输出了两遍
- 324浏览 收藏
-
- 文章 · python教程 | 1星期前 | 默认值 · python · 数据建模 · dataclass · default_factory · field · Python 数据类 Field 可变默认值 dataclass default_factory
- Python dataclass 默认值完整工作流:从可变默认值到 default_factory
- 228浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- ljg-skills
- ljg-skills 是李继刚开源的 AI 技能与提示词集合,面向大模型使用者整理了一批可复用的 prompt、角色设定和任务技能模板,适合用于学习提示词设计、搭建个人 AI 工作流和沉淀团队常用智能体能力。
- 2937次使用
-
- MELO音乐
- MELO音乐是一站式AI视频与音乐制作助手,对标suno, udio的高品质体验。提供伴奏生成、原创写词、无损导出、哼唱识曲、混音变声等全套音频与短视频编辑工具。无论是流行Kpop、电音说唱、民谣古风、摇滚儿歌还是商用轻音乐,MELO为你免费谱曲,轻松做同款!
- 2718次使用
-
- UniScribe
- UniScribe 是一款 AI 音视频转文字与内容整理工具,支持上传音频、视频文件或粘贴 YouTube 链接,自动生成转写文本、摘要、思维导图和关键问题,并支持多格式导出,适合会议记录、课程学习、访谈整理和内容创作复盘。
- 2652次使用
-
- 剧云
- 剧云是专业中文剧本创作平台,安全稳定运行十余年,集成AI编剧、剧本医生审核、人物小传、剧情关系图、大纲编写、多人协作、Word导入导出、版权管控功能,数据安全防护,轻松高效创作剧本。
- 2884次使用
-
- 万象有声
- 万象有声,一个专为有声创作者打造的新一代智能有声内容创作平台。平台提供专业的智能拆章、智能画本编辑、AI配音、AI生成音效、后期制作、智能对轨、智能审听等有声创作全流程工具,可以帮助创作者高效、低成本创作出引人入胜的有声作品。立即体验,让有声书制作更简单!
- 2828次使用
-
- Python监控网页状态:requests异常处理实战
- 2026-05-29 501浏览
-
- TensorFlow模型部署为API的TF Serving方法
- 2026-05-26 501浏览
-
- Python字符串编码转换:encode与decode详解
- 2026-05-16 501浏览
-
- TensorFlow裁剪无用算子方法详解
- 2026-05-15 501浏览
-
- httpx 如何设置代理认证(Proxy-Authorization)
- 2026-05-05 501浏览

