官方定义
迪米特法则(Law of Demeter,LoD)是1987年秋天由lan Holland 在美国东北大学的一个叫做迪米特项目设计提出的,它要求一个对象应该对其他对象有最少的了解,所以迪米特法则又叫做最少只是原则(Least Knowledge Principle,LKP)
一个对象应该对其他对象有最少的了解
只与直接的朋友通信
基本介绍
上面是直接的朋友? 上面是朋友?
只要有两个对象有依赖关系,就是朋友关系
直接的朋友?
- 成员变量
- 方法的参数类型
- 方法的返回值类型
前置 - 类的依赖关系
两个类? 具有依赖关系?
凡是类中用到了对方
注意事项
- 迪米特法则的核心是降低类之间的耦合
- 从被依赖者的角度来说,尽量将逻辑封装在类的内部,对外除了提供的public方法,不泄露任何信息
- 从依赖者的角度来说,只依赖应该依赖的对象
- 切忌不要为了用而用