1)一个对象应该对其它对象保持最少的了解
2)类与类关系越密切,耦合度越大
3)迪米特法则又称为最少知道原则,就是一个类对自己依赖的类知道的越少越好。
4)更简单的定义就是:只与直接朋友通信
5)直接朋友:每个对象都会与其它对象有耦合关系,只要两个对象之间有耦合,我们就说这两个对象之间就是朋友关系。耦合的方式有很多,依赖,关联,组合,聚合等。我们称出现成员变量,方法参数,方法返回值中的类为直接朋友,出现局部变量的类不是直接朋友。也就是陌生的类最好不要以局部变量的形式出现在类内部。
举例说明:
打印出学校总部员工ID和学院员工的id
//学校总部员工的javaBean
class Employee{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
//学院的员工类javaBean
class CollegeEmployee{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
//管理学院员工的管理类
class CollegeManager{
public List<CollegeEmployee> getAllEmployee(){
ArrayList<CollegeEmployee> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
CollegeEmployee collegeEmployee = new CollegeEmployee();
collegeEmployee.setId("学院员工id="+i);
list.add(collegeEmployee);
}
return list;
}
}
//schoolManager类的直接朋友有Employee CollegeManager
//CollegeEmployee是一个陌生类 不是直接朋友 违背了迪米特法则
class SchoolManager{
public List<Employee> getAllEmployee(){
ArrayList<Employee> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Employee employee = new Employee();
employee.setId("学校员工的id="+i);
list.add(employee);
}
return list;
}
void printAllEmployee(CollegeManager sub){
List<CollegeEmployee> allEmployee = sub.getAllEmployee();
//获取学院的员工
System.out.println("-----学院员工-----");
for(CollegeEmployee e:allEmployee){
System.out.println(e.getId());
}
List<Employee> allEmployee1 = this.getAllEmployee();
System.out.println("-----学校总部员工-----");
for(Employee e:allEmployee1){
System.out.println(e.getId());
}
}
}
//学校总部员工的javaBean
class Employee{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
//学院的员工类javaBean
class CollegeEmployee{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
//管理学院员工的管理类
class CollegeManager{
public List<CollegeEmployee> getAllEmployee(){
ArrayList<CollegeEmployee> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
CollegeEmployee collegeEmployee = new CollegeEmployee();
collegeEmployee.setId("学院员工id="+i);
list.add(collegeEmployee);
}
return list;
}
public void printEmployee(){
List<CollegeEmployee> allEmployee = getAllEmployee();
System.out.println("----学院员工----");
for(CollegeEmployee e:allEmployee){
System.out.println(e.getId());
}
}
}
//schoolManager类的直接朋友有Employee CollegeManager
//CollegeEmployee是一个陌生类 不是直接朋友 违背了迪米特法则,在CollegeEmployee类中封装好,不对外暴露,直接用对象调用
class SchoolManager{
public List<Employee> getAllEmployee(){
ArrayList<Employee> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Employee employee = new Employee();
employee.setId("学校员工的id="+i);
list.add(employee);
}
return list;
}
void printAllEmployee(CollegeManager sub){
//获取学院的员工
sub.printEmployee();
List<Employee> allEmployee1 = this.getAllEmployee();
System.out.println("-----学校总部员工-----");
for(Employee e:allEmployee1){
System.out.println(e.getId());
}
}
}