迪米特法则(Law of Demeter)又叫作最少知识原则(Least Knowledge Principle 简写LKP),一个类对于其他类知道的越少越好,就是说一个对象应当对其他对象有尽可能少的了解,只和朋友通信,不和陌生人说话。英文简写为: LoD.
关于方法指针,有意思的事情是:它们的使用可能就表明代码违反了迪米特法则。
The interesting thing about method Pointers is that their use can be an indication that the code violates the Law of Demeter.
在清单9中,可以看到这些代码演示了迪米特法则——如何用它洗劫人们的钱包!
In Listing 9, you can see how this code demonstrates the Law of Demeter — and how it could be used to wreak havoc with people's wallets!
迪米特法则使用只与直接朋友对话这句格言指出:我们应当避免调用由另一个对象方法返回的对象上的方法。
Using the motto Talk only to immediate friends, the Law of Demeter states that we should avoid invoking methods of an object that was returned by another object's method.
应用推荐