Demeter's law is a principle in object-oriented design. Its goal is to reduce the direct dependence between objects . It emphasizes 一个对象应该尽量减少与其他对象之间的直接交互
that, 只与自己的直接朋友进行通信
(the so-called friend relationship between objects means that 耦合关系
there are many ways of coupling: dependence, association, Combination, aggregation, etc. We call it 出现成员变量,方法参数,方法返回值中的类为直接朋友
, while 出现在局部变量中的类不是直接朋友
), this can prevent an object from overly understanding the internal structure of other objects, thereby reducing the coupling and dependence of the code , improving the maintainability of the code, reducing the complexity of the system, and being convenient Perform unit testing and refactoring.
Example:
We create student, class, school respectively, establish a direct friend relationship between student and class, and establish a direct friend relationship between school and class. However, there is no interactive relationship between student and school, which reduces the coupling between classes.
package druidResources;
import java.util.ArrayList;
import java.util.List;
// 学生类
class Student {
private String name;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
// 班级类
class Class {
//实现班级和学生交互
private List<Student> students;
public Class() {
students = new ArrayList<>();
}
public void addStudent(Student student) {
students.add(student);
}
public List<Student> getStudents() {
return students;
}
}
// 学校类
class School {
//实现班级和学校交互
private List<Class> classes;
public School() {
classes = new ArrayList<>();
}
public void addClass(Class clazz) {
classes.add(clazz);
}
// 获取学校中所有学生的姓名
public List<String> getAllStudentNames() {
List<String> names = new ArrayList<>();
for (Class clazz : classes) {
for (Student student : clazz.getStudents()) {
names.add(student.getName());
}
}
return names;
}
}
public class LawOfDemeter {
public static void main(String[] args) {
// 创建学校对象
School school = new School();
// 创建班级对象
Class class1 = new Class();
Class class2 = new Class();
// 创建学生对象
Student student1 = new Student("张三");
Student student2 = new Student("李四");
Student student3 = new Student("王五");
// 添加学生到班级
class1.addStudent(student1);
class1.addStudent(student2);
class2.addStudent(student3);
// 添加班级到学校
school.addClass(class1);
school.addClass(class2);
// 获取学校中所有学生的姓名
List<String> names = school.getAllStudentNames();
// 打印学生姓名
for (String name : names) {
System.out.println(name);
}
}
}
Output:
张三
李四
王五