nest 中使用的设计模式
IOC:nversion of Control 字面意思是控制反转,具体定义是高层模块不应该依赖低层模块,二者都应该依赖其抽象;抽象不应该依赖细节;细节应该依赖抽象。
是面向对象过程中的设计原则,主要用于降低代码间的耦合度,最常见的方式就是依赖注入。
DI:(Dependency Injection)其实和 IoC 是同根生,这两个原本就是一个东西,只不过由于控制反转概念比较含糊(可能只是理解为容器控制对象这一个层面,很难让人想到谁来维护对象关系),所以 2004 年大师级人物 Martin Fowler 又给出了一个新的名字:“依赖注入”。 类 A 依赖类 B 的常规表现是在 A 中使用 B 的 instance。
根据上面的说法查询 deepseek 解释后,简易版理解方式:
传统代码:程序一步一步自己编写并调用各种函数以实现功能。
控制反转:核心是控制权的转移;程序流程不再由开发者直接控制,而是交给框架或容器管理。
依赖注入:核心是解耦依赖关系;将类所需的依赖从外部注入,而非类内部直接创建。
传统代码示例
class A {
name: string
constructor(name: string) {
this.name = name
}
}
class B {
age:number
entity:A
constructor (age:number) {
this.age = age;
this.entity = new A('路人甲')
}
}
const c = new B(18)
用依赖注入的方式改写后的代码:
// 重点是将B对A的依赖从内部创建改为外部传入:
class A {
name: string
constructor(name: string) {
this.name = name
}
}
class B {
age: number
entity: A // 不再自己创建,而是等待注入
// 新增entity参数,由外部传入
constructor(age: number, entity: A) {
this.age = age;
this.entity = entity; // 注入A的实例
}
}
// 使用时的变化:
const a = new A('路人甲'); // 先创建依赖项
const c = new B(18, a); // 再通过构造函数注入
// 也可以轻松替换不同版本的A:
const testA = new A('路人乙');
const testB = new B(20, testA);
关键改动点:
- B 的构造函数新增 entity 参数
- 创建 B 时需要显式传入 A 的实例
- B 不再与 A 的创建过程耦合
优势:
- 🎯 想换 A 时不用改 B 的代码(比如改成 A(' 路人 '))
- 🔧 测试时可以用 MockA 代替真实 A
- 🔗 明确显示出 B 依赖 A 的关系
