zchfeng / Front-End-note

1 stars 0 forks source link

迪米特原则 #18

Open zchfeng opened 1 year ago

zchfeng commented 1 year ago

米特原则也叫最少知道原则, 一个类应该对其他对象保持最少的了解。 通俗来讲,就是一个类对自己依赖的类知道的越少越好。因为类与类之间的关系越密切,耦合度越大,当一个类发生改变时,对另一个类的影响也越大。

zchfeng commented 1 year ago

举例:

class Computer {
  public savaCurrentTask() {
    /// ...
  }

  public closeService() {
    /// ...
  }

  public closeScreen() {
    /// ...
  }

  public closePower() {
    /// ...
  }

  public close() {
    this.savaCurrentTask();
    this.closeService();
    this.closeScreen();
    this.closePower();
  }
}

class User {
  public clickClose() {
    let computer = new Computer();
    computer.closeService();
    computer.closePower();

    // 或者
    computer.closeService();
    computer.close();
   // 或者
    computer.closePower();
    computer.close();
  }
}

User使用Computer需要理解Computer所有的方法。

zchfeng commented 1 year ago

使用迪米特原则:

class ComputerDMT {
  private savaCurrentTask() {
    /// ...
  }

  private closeService() {
    /// ...
  }

  private closeScreen() {
    /// ...
  }

  private closePower() {
    /// ...
  }

  public close() {
    this.savaCurrentTask();
    this.closeService();
    this.closeScreen();
    this.closePower();
  }
}

class UserDMT {
  public clickClose() {
    let computer = new ComputerDMT();
    computer.close();
  }
}

ComputerDMT只抛出了close方法,UserDMT 也只需要知道close方法

zchfeng commented 1 year ago

迪米特法则的优点和缺点

降低了类之间的耦合度,提高了模块的相对独立性。 由于亲合度降低,从而提高了类的可复用率和系统的扩展性。 但是,过度使用迪米特法则会使系统产生大量的中介类,从而增加系统的复杂性,使模块之间的通信效率降低。所以,在釆用迪米特法则时需要反复权衡,确保高内聚和低耦合的同时,保证系统的结构