这里以考试科目作为元素
public interface Course { //接受老师访问者 public void accept(TeacherView view); }
public class MathCourse implements Course { int score; public MathCourse() { Random random = new Random(); score = random.nextInt(100); } //这里有反转,把自己交给具体的访问者去处理 @Override public void accept(TeacherView teacherView) { teacherView.view(this); } public int getScore() { return score; } }
public class EnglishCourse implements Course { int score; public EnglishCourse() { Random random = new Random(); score = random.nextInt(100); } @Override public void accept(TeacherView teacherView) { teacherView.view(this); } public int getScore() { return score; } }
public interface TeacherView { /** * 访问英语 * @param course */ void view(EnglishCourse course); /** * 访问数学 * @param course */ void view(MathCourse course); }
public class ChargeTeacher implements TeacherView { List<Integer> englist = new ArrayList<>(); List<Integer> mathlist = new ArrayList<>(); @Override public void view(EnglishCourse course) { englist.add(course.getScore()); System.out.println("当前人数的数学平均分" + englist.stream().mapToDouble(x -> x.longValue()).average().orElse(0D)); } @Override public void view(MathCourse course) { mathlist.add(course.getScore()); System.out.println("当前人数的英语平均分" + mathlist.stream().mapToDouble(x -> x.longValue()).average().orElse(0D)); } }
public class EnglishTeacher implements TeacherView { @Override public void view(EnglishCourse course) { System.out.println("英语成绩:" + course.getScore()); } @Override public void view(MathCourse course) { } }
public class MathTeacher implements TeacherView { @Override public void view(EnglishCourse course) { } @Override public void view(MathCourse course) { System.out.println("数学成绩:" + course.getScore()); } }
public class ScoreReport { List<Course> list = new ArrayList<>(); public ScoreReport() { list.add(new EnglishCourse()); list.add(new EnglishCourse()); list.add(new MathCourse()); list.add(new MathCourse()); } public void report(TeacherView teacherView) { for (Course course : list) { course.accept(teacherView); } } }
public class TestMain { public static void main(String[] args) { ScoreReport scoreReport = new ScoreReport(); // 数学老师访问成绩 scoreReport.report(new MathTeacher()); // 英语老师访问成绩 scoreReport.report(new EnglishTeacher()); // 班主任访问成成绩 scoreReport.report(new ChargeTeacher()); } } 数学成绩:44 数学成绩:84 英语成绩:71 英语成绩:10 当前人数的数学平均分71.0 当前人数的数学平均分40.5 当前人数的英语平均分44.0 当前人数的英语平均分64.0