作者:男人好好疼h爱你的女人吧 | 来源:互联网 | 2023-10-10 19:05
迪米特原则
一个对象对其他对象最少的了解,又叫做最少知道的原则
尽量降低,类与类之间的耦合,类之间的弱耦合,如果大量使用迪米特法则
生活中的迪米特原则
例如:Boos 让部门经理我要你们部门的人的所有材料,显然Boos不会亲自干这个事了,Boos通知部门经理,部门经理在通知工作人员你们把材料交到我的手中,经理整理完事之后,进行汇总,在交到Boos手中 Boos不知道过程,我只要结果,我不认识你们部门的所有人,我只认识你们领导
代码中的迪米特原则
我们模仿这样一个场景 Boos下发指令找团队负责人,团队负责人去收集个人信息
public class Boos {public void command(TeamLeader teamLeader){List<String> employee &#61; teamLeader.getEmployee();for (String s : employee) {System.out.println(s);}}
}
public class TeamLeader {public List<String> getEmployee(){Employee employee &#61; new Employee();List<String> curriculum &#61; employee.getCurriculum();return curriculum;}
}
public class Employee {public List<String> getCurriculum(){return Arrays.asList("1","2");}
}
public class Test {public static void main(String[] args) {Boos boos&#61;new Boos();boos.command(new TeamLeader());}
}
这样根据Test Boos只给部门领导下发了命令&#xff0c;部门领导接触了那些人