2019独角兽企业重金招聘Python工程师标准>>>
迪米特法则(Law of Demeter),Demeter是古希腊神话中的农业、谷物和丰收的女神,奥林匹斯十二主神之一。它的名字源于迪米特计划, 该项目是为纪念Demeter,“distribution-mother”和希腊农业女神而命名的,以表示自下而上的编程哲学。
迪米特法具体含义可以从以下几句话中理解:
- Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
- Each unit should only talk to its friends; don't talk to strangers.
- Only talk to your immediate friends.
即:
- 每个单元对其他单元的了解应该是非常有限的:只和当前单元关系密切的单元联系。
- 每个单元只和朋友讲话,而不合陌生人交谈。
- 只和你的直接朋友讲话。
我们引用例子来看一下:
//总公司员工class Employee{private String id;public void setId(String id){this.id = id;}public String getId(){return id;}}//分公司员工class SubEmployee{private String id;public void setId(String id){this.id = id;}public String getId(){return id;}}class SubCompanyManager{public List getAllEmployee(){List list = new ArrayList();for(int i=0; i<100; i++){SubEmployee emp = new SubEmployee();//为分公司人员按顺序分配一个IDemp.setId("分公司"+i);list.add(emp);}return list;}}class CompanyManager{public List getAllEmployee(){List list = new ArrayList();for(int i=0; i<30; i++){Employee emp = new Employee();//为总公司人员按顺序分配一个IDemp.setId("总公司"+i);list.add(emp);}return list;}public void printAllEmployee(SubCompanyManager sub){List list1 = sub.getAllEmployee();for(SubEmployee e:list1){System.out.println(e.getId());}List list2 = this.getAllEmployee();for(Employee e:list2){System.out.println(e.getId());}}}public class Client{public static void main(String[] args){CompanyManager e = new CompanyManager();e.printAllEmployee(new SubCompanyManager());}}
修改后如下:
class SubCompanyManager{ public List<SubEmployee> getAllEmployee(){ List<SubEmployee> list = new ArrayList<SubEmployee>(); for(int i=0; i<100; i++){ SubEmployee emp = new SubEmployee(); //为分公司人员按顺序分配一个ID emp.setId("分公司"+i); list.add(emp); } return list; } public void printEmployee(){ List<SubEmployee> list = this.getAllEmployee(); for(SubEmployee e:list){ System.out.println(e.getId()); } }
} class CompanyManager{ public List<Employee> getAllEmployee(){ List<Employee> list = new ArrayList<Employee>(); for(int i=0; i<30; i++){ Employee emp = new Employee(); //为总公司人员按顺序分配一个ID emp.setId("总公司"+i); list.add(emp); } return list; } public void printAllEmployee(SubCompanyManager sub){ sub.printEmployee(); List<Employee> list2 = this.getAllEmployee(); for(Employee e:list2){ System.out.println(e.getId()); } }
}
遵循迪米特法则可以降低类之间的耦合,每个类减少不必要的依赖。但是如果过度使用,会有大量的中介类,所以应该权衡利弊,不可盲目。
引用:
http://wiki.jikexueyuan.com/project/java-design-pattern-principle/principle-5.html
https://en.wikipedia.org/wiki/Law_of_Demeter