IOC控制反转&DI依赖注入

140 阅读1分钟

概念: IOC(Inversion of Control)控制反转,就是面对对象的一种设计原则,用来降低模块之间的耦合度,DI(Dependency Inject)是IOC的一种体现,本质是定义一个容器去调度各个模块间的关系从而降低模块间的耦合

class A {
    a:string
    constructor(){
        this.a = 'pp'
    }
}
class B {
    b:string
    constructor(){
        this.b = new A().a
    }
}

class C {
    c:string
    constructor(){
        this.c = new A().a
    }
}

其中B,C类与A类是强耦合关系,如果A类改变,BC类也需要跟着改变

//代码修改

class A {
  a: string;
  constructor(value) {
    this.a = value;
  }
}

class Container {
  mo: any;
  constructor() {
    this.mo = {};
  }

  provide(key: string, mo: any) {
    this.mo[key] = mo;
  }

  get(key: string) {
    return this.mo[key];
  }
}

const mo = new Container();

mo.provide("a", new A("aa"));
mo.provide("b", new A("bb"));

class C {
  a: any;
  b: any;
  constructor(mo: Container) {
    this.a = mo.get("a");
    this.b = mo.get("b");
  }
}

修改后的代码新增了一个Container类(我们称之为IOC容器),引入容器之后A,C模块间的代码逻辑就已经解耦,可以单独拓展其他功能或业务逻辑,也可以加入其他模块,有点类似发布订阅模式