IOC
Inversion of Control 即控制反转
具体定义是高层模块不应该依赖低层模块,二者都应该依赖其抽象;抽象不应该依赖细节;细节应该依赖抽象。
DI
Dependency Injection 即依赖注入
其实和IOC原本就是一个东西,只不过由于控制反转概念比较模糊(人们常理解为容器控制对象,没有联想到谁来维护对象关系);所以提出了“依赖注入”这个概念。
类A 依赖 类B 的常规表现就是: 在类A中使用了类B的实例。
未使用控制反转和依赖注入的代码
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)
console.log(c.entity.name)
在代码中,类B的创建依赖了类A的instance,两者的代码耦合度非常高。当两者之间的业务逻辑复杂程度增加的情况下,维护成本与代码可读性都会随着增加,并且很难再多引入额外的模块进行功能拓展。
使用IOC容器解决上面的问题
class A {
name: string
constructor(name: string) {
this.name = name
}
}
class B {
name: string
constructor(name: string) {
this.name = name
}
}
// 使用容器进行解耦
class Container {
modeuls: any
constructor() {
this.modeuls = {}
}
provide(key: string, modeuls: any) {
this.modeuls[key] = modeuls
}
inject(key) {
return this.modeuls[key]
}
}
const container = new Container()
container.provide('a', new A('小张'))
container.provide('b', new B('小李'))
class C {
a: any
b: any
constructor(container: Container) {
this.a = container.inject('a')
this.b = container.inject('b')
}
}
new C(container)
写了一个中间件,通过Container来收集依赖,主要是为了解耦,减少维护成本。