迪米特法则: 最少知道原则,即一个类对自己依赖的类知道的越少越好
迪米特法则代码1:(违反了迪米特法则,不推荐使用)
/**
* 学校总部员工类
*/
class Employee {
// 员工编号
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
/**
* 学校分院员工类
*/
class CollegeEmployee {
// 员工编号
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
/**
* 学校分院员工管理类
*/
class CollegeManager {
// 分院员工列表
public List<CollegeEmployee> getAllEmployee() {
List<CollegeEmployee> employeeList = new ArrayList<CollegeEmployee>();
for (int i = 1; i <= 10; i++) {
CollegeEmployee employee = new CollegeEmployee();
employee.setId(" 分院员工编号 = " + i);
employeeList.add(employee);
}
return employeeList;
}
}
/**
* 学校总部员工管理类
*/
class SchoolManager {
// 总院员工列表
public List<Employee> getAllEmployee() {
List<Employee> employeeList = new ArrayList<Employee>();
for (int i = 1; i <= 10; i++) {
Employee employee = new Employee();
employee.setId(" 总部员工编号 = " + i);
employeeList.add(employee);
}
return employeeList;
}
/**
* CollegeManager 和 SchoolManager 不是直接的关系, CollegeManager 是以局部变量出现在
* SchoolManager, 违反了迪米特法则
*
* @param collegeManager
*/
void printAllEmployee(CollegeManager collegeManager) {
List<CollegeEmployee> employeeList = collegeManager.getAllEmployee();
System.out.println("-分院员工列表------------- ");
for (CollegeEmployee c : employeeList) {
System.out.println(c.getId());
}
List<Employee> employeeList2 = this.getAllEmployee();
System.out.println("-总院员工列表------------- ");
for (Employee c : employeeList2) {
System.out.println(c.getId());
}
}
}
public static void main(String[] args) {
SchoolManager schoolManager = new SchoolManager();
schoolManager.printAllEmployee(new CollegeManager());
}
解析:对于被依赖的类,不管有多么复杂,都尽量将逻辑封装在类的内部对外除了提供public方法,不对外泄露任何信息;上方代码CollegeManager 和 SchoolManager 不是直接的关系,违反了迪米特法则;