底层原理 十一月 17, 2020

设计模式的七大原则——迪米特法则(上)

文章字数 10k 阅读约需 9 mins. 阅读次数 1000000

迪米特法则: 最少知道原则,即一个类对自己依赖的类知道的越少越好

迪米特法则代码1:(违反了迪米特法则,不推荐使用)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
 * 学校总部员工类
 */
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 不是直接的关系,违反了迪米特法则;

0%