目录
例子
有一个学校,下属有各个学院和总部,现要求打印出学校总部员工ID和学院员工的id
- package com.atguigu.demeter;
-
- import java.util.ArrayList;
- import java.util.List;
-
- public class Demeter1 {
-
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- //创建 SchoolManager 对象
- SchoolManager schoolManager = new SchoolManager();
- //输出学院员工 和 学校总员工 的id
- schoolManager.printAllEmployee(new CollegeManager());
-
- }
-
- }
-
-
- class Employee {
- private String id;
-
- public void setId(String id) {
- this.id = id;
- }
-
- public String getId() {
- return id;
- }
- }
-
-
- class CollegeEmployee {
- private String id;
-
- public void setId(String id) {
- this.id = id;
- }
-
- public String getId() {
- return id;
- }
- }
-
- //管理学院员工的管理类
- class CollegeManager {
- public List
getAllEmployee() { - List
list = new ArrayList(); - for (int i = 0; i < 10; i++) {
- CollegeEmployee emp = new CollegeEmployee();
- emp.setId("学院员工= " + i);
- list.add(emp);
- }
- return list;
- }
- }
-
- //学校管理类
- /*
- * SchoolManager直接朋友:Employee、CollegeManager
- * 非直接朋友(违反迪米特法则):CollegeEmployee
- */
- class SchoolManager {
- //返回学校总部的员工
- public List
getAllEmployee() { - List
list = new ArrayList(); - for (int i = 0; i < 5; i++) {
- Employee emp = new Employee();
- emp.setId("学校总部员工id= " + i);
- list.add(emp);
- }
- return list;
- }
- //该方法完成输出学校总部和学院员工的信息
- void printAllEmployee(CollegeManager sub) {
- //分析问题
- //1。这里的 CollegeEmployee 不是 SchoolManager的直接朋友
- //2。CollegeEmployee 是以局部变量方式出现在 SchoolManager
- //3,违反了 迪米特法则
- List
list1 = sub.getAllEmployee(); - System.out.println("------------分公司员工------------");
- for (CollegeEmployee e : list1) {
- System.out.println(e.getId());
- }
- List
list2 = this.getAllEmployee(); - System.out.println("------------学校总部员工------------");
- for (Employee e : list2) {
- System.out.println(e.getId());
- }
- }
- }
分析
例子改进
- //管理学院员工的管理类
- class CollegeManager {
- public List
getAllEmployee() { - List
list = new ArrayList(); - for (int i = 0; i < 10; i++) {
- CollegeEmployee emp = new CollegeEmployee();
- emp.setId("学院员工= " + i);
- list.add(emp);
- }
- return list;
- }
-
- public void print() {
- List
list1 = this.getAllEmployee(); - System.out.println("------------分公司员工------------");
- for (CollegeEmployee e : list1) {
- System.out.println(e.getId());
- }
- }
- }
-
- //学校管理类
- /*
- * SchoolManager直接朋友:Employee、CollegeManager
- * 非直接朋友(违反迪米特法则):CollegeEmployee
- */
- class SchoolManager {
- //返回学校总部的员工
- public List
getAllEmployee() { - List
list = new ArrayList(); - for (int i = 0; i < 5; i++) {
- Employee emp = new Employee();
- emp.setId("学校总部员工id= " + i);
- list.add(emp);
- }
- return list;
- }
- //该方法完成输出学校总部和学院员工的信息
- void printAllEmployee(CollegeManager sub) {
- //解决方法
- //将获取员工id放到CollegeEmployee类中,调用方法即可
- sub.print();
-
- List
list2 = this.getAllEmployee(); - System.out.println("------------学校总部员工------------");
- for (Employee e : list2) {
- System.out.println(e.getId());
- }
- }
- }