当前位置:首页 > 文章列表 > 文章 > python教程 > 分解依赖倒置、IoC 和 DI

分解依赖倒置、IoC 和 DI

2025-01-20 16:51:43 0浏览 收藏

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

分解依赖倒置、IoC 和 DI

本文深入探讨 NestJS 依赖注入系统,并阐明依赖倒置原则 (DIP)、控制反转 (IoC) 和依赖注入 (DI) 的概念及其关联。这三个概念看似相似,实则各有侧重,相互关联却又解决不同的问题。本文旨在帮助读者理清这些概念,并理解它们如何协同工作。


  1. 依赖倒置原则 (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);
    }
}

问题:

  1. 紧密耦合:Notification 直接依赖 EmailService
  2. 难以扩展:切换到 SMSServicePushNotificationService 需要修改 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 的优势

  • 灵活性:无需修改高层模块即可替换实现。
  • 可测试性:使用模拟对象替换真实依赖项进行测试。
  • 可维护性:低层模块的更改不会影响高层模块。

  1. 控制反转 (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 的问题:

  1. 紧密耦合:Notification 类直接创建并依赖 SMSService 类。
  2. 灵活性低:切换到其他实现需要修改 Notification 类。
  3. 难以测试:模拟依赖项用于单元测试比较困难,因为依赖项是硬编码的。

使用 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 的优势:

  1. 松散耦合:类不创建其依赖项,从而减少对特定实现的依赖。
  2. 易于切换实现:用 EmailService 替换 SMSService 而无需修改核心类。
  3. 提高可测试性:在测试期间注入模拟或 Mock 依赖项。

  1. 依赖注入 (DI)

DI 是一种技术,对象从外部源接收其依赖项,而不是自己创建它们。

DI 是 IoC 的一种实现方式。它允许开发人员通过多种方式将依赖项“注入”到类中:

  1. 构造函数注入:依赖项通过构造函数传递。
  2. Setter 注入:依赖项通过公共方法设置。
  3. 接口注入:依赖项通过接口提供。

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帮义乌老板重新设计全红婵“丑鱼”拖鞋
下一篇
我用AI帮义乌老板重新设计全红婵“丑鱼”拖鞋
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    543次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    516次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    500次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    485次学习
查看更多
AI推荐
  • ChatExcel酷表:告别Excel难题,北大团队AI助手助您轻松处理数据
    ChatExcel酷表
    ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
    7517次使用
  • Any绘本:开源免费AI绘本创作工具深度解析
    Any绘本
    探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
    7943次使用
  • 可赞AI:AI驱动办公可视化智能工具,一键高效生成文档图表脑图
    可赞AI
    可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
    7750次使用
  • 星月写作:AI网文创作神器,助力爆款小说速成
    星月写作
    星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
    9686次使用
  • MagicLight.ai:叙事驱动AI动画视频创作平台 | 高效生成专业级故事动画
    MagicLight
    MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
    8476次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码