Typescript-DI&IOC2016-07-11 23:03Typescript
  • IOC 是一种思想
  • DI 是一种设计模式
  • DI 是实现 IOC 的方法

DI - Dependency Injection - 依赖注入

小明是个人:

import Person from '...'

class Ming extends Person {
  private name;
  private age;

  read = () => {};
  play = () => {};
  wechat = () => {};
}

小明喜欢有个 Iphone20:

import Iphone from '...'

class Iphone20 extends Iphone {
  read = (user) => `${user} is reading`;
  play = (user) => `${user} is playing`;
  wechat = (user) => `${user} is using wechat`;
}

小明把每个动作都用到了手机:

import Iphone20 from '...'
import Person from '...'

class Ming extends Person {
  private name;
  private age;

  read = () => new Iphone20().read(this.name);
  play = () => new Iphone20().play(this.name);
  wechat = () => new Iphone20().wechat(this.name);
}

某天小明买了台小米, 突然发现之前耦合度过高居然要改三行代码.

于是小明决定将 phone 作为自己的一个 property

import Iphone20 from '...' 
import Person from '...'

class Ming extends Person {
  private name;
  private age;
  private phone;  // 新加了一个 Properties

  constructor() => {
    this.phone = new Iphone20();
  };

  read = () => this.phone.read(this.name); 
  play = () => this.phone.play(this.name);
  wechat = () => this.phone.wechat(this.name);
}

但是还是在类内部初始化了 Iphone20 这个类, 那么我们可以将其优化一下:

import Iphone20 from '...' 
import Person from '...'

class Ming extends Person {
  private name;
  private age;
  private phone;  // 新加了一个 Properties

  // 要求外部直接传进来一个 iPhone20, 实例化移动到了外部
  constructor(phone: Iphone20) => {
    this.phone = phone;
  };

  // ...
}

但是这样还不够, 希望将手机再首抽象一些:

export interface interfacePhone {
  getUsers(): Promise<User[]>
}

export class Phone implements interfacePhone {
  getUsers(): Promise<User[]> { ... }
}
class Ming extends Person {
    
  // ...
  
  constructor(phone: interfacePhone) {
    /* 这里变为引用抽象类 interfacePhone */
    /* 抽象类 interfacePhone 以后甚至可以再进行抽象, 比如接受阅读器等设备 */

    this.phone = phone;
  }

  // ...
}

到此为止的全部操作逻辑:

Powered by Remix
|
Designed by szhshp
|
Copyright © szhshp 2022