本文深入探讨 NestJS 依赖注入系统,并阐明依赖倒置原则 (DIP)、控制反转 (IoC) 和依赖注入 (DI) 的概念及其关联。这三个概念看似相似,实则各有侧重,相互关联却又解决不同的问题。本文旨在帮助读者理清这些概念,并理解它们如何协同工作。
定义:
高层模块不应该依赖于低层模块;两者都应该依赖于抽象。抽象不应该依赖于细节;细节应该依赖于抽象。
在软件开发中,高层模块负责核心业务逻辑,而低层模块处理具体的实现细节(例如文件系统、数据库或 API)。若无 DIP,高层模块直接依赖于低层模块,导致紧密耦合,从而:
DIP 颠覆了这种依赖关系。高层和低层模块都依赖于共享的抽象(接口或抽象类),而不是高层模块直接控制低层实现。
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)
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); } }
问题:
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!")
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!");
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 的问题:
在使用 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 的优势:
DI 是一种技术,对象从外部源接收其依赖项,而不是自己创建它们。
DI 是 IoC 的一种实现方式。它允许开发人员通过多种方式将依赖项“注入”到类中:
使用 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!")
使用 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的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号