迪米特法则(LOD)

迪米特法则(LOD)

迪米特法则 #

迪米特法则(Law of Demeter, LOD),也叫最小知识原则:The Least Knowledge Principle。

Each unit should have only limited knowledge about other units: only units “closely” related to the current unit. Each unit should only talk to its friends; Don’t talk to strangers.

每个模块(unit)只应该了解那些与它关系密切的模块(units: only units “closely” related to the current unit)的有限知识(knowledge)。或者说,每个模块只和自己的朋友“说话”(talk),不和陌生人“说话”(talk)。

在面向对象里,可以这么说:

  1. 不该有直接依赖关系的类之间,不要有依赖;
  2. 有依赖关系的类之间,尽量只依赖必要的接口(也就是定义中的“有限知识”)。

Viewpoint #

From #

22 | 理论八:如何用迪米特法则(LOD)实现“高内聚、松耦合”?