1.定义
也称为最少知道原则,如果两个类在属性成员或者方法成员的出入参上没有关联,那么两个类就没有必要相互作用。这样,类之间的耦合度就越弱,就越容易被复用。
迪米特法则降低了类的复杂度和耦合,提高了代码的可维护性、可复用性以及可读性。

2.代码示例
(1).耦合

public class Boss {
public void commandCheckCourseNumber(Manager manager) {
List<Course> courseList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
courseList.add(new Course());
}
manager.checkCourseNumber(courseList);
}
}
public class Manager {
public void checkCourseNumber(List<Course> courseList) {
System.out.println("课程数量为" + courseList.size());
}
}
public class Course {
}
public class Test {
public static void main(String[] args) {
Boss boss = new Boss();
Manager manager = new Manager();
boss.commandCheckCourseNumber(manager);
}
}

(2).最少知道

public class Boss {
public void commandCheckCourseNumber(Manager manager) {
manager.checkCourseNumber();
}
}
public class Manager {
public void checkCourseNumber() {
List<Course> courseList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
courseList.add(new Course());
}
System.out.println("课程数量为" + courseList.size());
}
}
public class Course {
}
public class Test {
public static void main(String[] args) {
Boss boss = new Boss();
Manager manager = new Manager();
boss.commandCheckCourseNumber(manager);
}
}

1.3 迪米特法则_List