个人认为访问者设计模式就是根据访问者的不同,展现事物不同的特性
public abstract class User { public String name; //姓名 public String identity; //身份 public String clazz; //班级 public User(String name , String identity , String clazz){ this.name = name; this.identity = identity; this.clazz = clazz; } public abstract void accept(Visitor visitor); }
public class Teacher extends User{ public Teacher(String name , String identity , String clazz){ super(name,identity,clazz); } @Override public void accept(Visitor visitor) { visitor.visit(this); } //升本率 public double entranceRatio() { return BigDecimal.valueOf(Math.random() * 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); } }
public class Student extends User{ public Student(String name , String identity , String clazz){ super(name,identity,clazz); } @Override public void accept(Visitor visitor) { visitor.visit(this); } public int ranking() { return (int) (Math.random() * 100); } }
定义了一个抽象类User,Student 和 Teacher分别继承User 在accept方法中传入一个Visitor对象,根据Visitor对象的不同,观察Student和Teacher的角度也不同
public interface Visitor { //访问学生信息 void visit(Student student); //访问老师信息 void visit(Teacher teacher); }
定义一个访问者接口Visitor
public class Parent implements Visitor{ public void visit(Student student) { System.out.println("学生信息 姓名:"+student.name+" 班级: "+ student.clazz + " 排名: " + student.ranking()); } public void visit(Teacher teacher) { System.out.println("老师信息 姓名:"+teacher.name+" 班级: "+teacher.clazz+" 级别: " + teacher.identity); } }
public class Principal implements Visitor{ public void visit(Student student) { System.out.println("学生信息 姓名:"+student.name+" 班级: "+student.clazz); } public void visit(Teacher teacher) { System.out.println("老师信息 姓名:"+teacher.name+" 班级: "+teacher.clazz+" 升学率: " + teacher.entranceRatio()); } }
分别定义校长和家长两个访问者,两个访问者访问Student和Teacher的角度不同,校长更关注老师的升学率 ,而家长更加关注孩子的排名和老师的级别
public class DataView { List<User> userList = new ArrayList<User>(); public DataView() { userList.add(new Student("谢飞机", "重点班", "一年一班")); userList.add(new Student("windy", "重点班", "一年一班")); userList.add(new Student("大毛", "普通班", "二年三班")); userList.add(new Student("Shing", "普通班", "三年四班")); userList.add(new Teacher("BK", "特级教师", "一年一班")); userList.add(new Teacher("娜娜Goddess", "特级教师", "一年一班")); userList.add(new Teacher("dangdang", "普通教师", "二年三班")); userList.add(new Teacher("泽东", "实习教师", "三年四班")); } // 展示 public void show(Visitor visitor) { for (User user : userList) { user.accept(visitor); } }
public class Test { public static void main(String[] args) { DataView dataView = new DataView(); System.out.println("家长视角访问"); dataView.show(new Parent()); // 家长 System.out.println("校长视角访问"); dataView.show(new Principal()); // 校长 }
可以看出,在不同的访问者下,得到的内容是一样的.