nestjs 控制反转、依赖注入

1、全局安装typescript

npm install typescript -g 

2、全局安装ts-node

npm install ts-node -g

3、demo.ts

/**
*  B中代码的实现是依赖A的,两者之间的耦合度非常高,当两者之间的业务逻辑复杂程度增加的情况下
*  维护成本与代码的可读性都会随着增加,并且很难再多引入额外的模块进行功能扩展
*/

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 ('test');
    }
}

const c = new B(18);

console.log(c.entity.name);

4、demo.ts

// 通过中间件方式来收集依赖,实现解耦,减少维护成本


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

class C {
    name: string
    constructor(name: string){
        this.name = name;
    }
}

// 中间件用于解耦
class Container {
    modules: any
    constructor () {
        this.modules = {};
    }
    
    provide(key: string, modules: any){
        this.modules[key] = modules;
    }
    
    get(key:string){
        return this.modules[key];
    }
}

// 实例化中间件类,依赖注入
const mo = new Container();
mo.provide('a', new A('test1'));
mo.provide('c', new C('test2'));

class B {
    a: any
    c:any
    constructor(container: Container){
        this.a = container.get('a');
        this.c = container.get('c');
    }
}

const b = new B(mo);

console.log(b.a.name);
console.log(b.c.name);

你可能感兴趣的:(javascript,开发语言,ecmascript)