举个老师跟学生的简单例子,老师是被观察者,学生是观察者。老师布置作业,所有订阅消息的学生都能收到老师布置的作业。
/** * teacher class extends observable * * @Author: yzhang * @Date: 2019/8/12 16:03 */ public class Teacher extends Observable { private String content; public void setHomework(final String content) { this.content = content; System.out.println("布置的作业是:" + content); /** * 标记对象已更改,更改后才能通知 */ setChanged(); /** * 通知观察者,会调用观察者update方法 */ notifyObservers(); } public String getContent() { return this.content; } }
/** * student class implement observer * * @Author: yzhang * @Date: 2019/8/12 16:03 */ public class Student implements Observer { private final Observable observable; private final String name; public Student(Observable observable, String name) { this.observable = observable; this.name = name; observable.addObserver(this); } @Override public void update(Observable o, Object arg) { if (o instanceof Teacher) { Teacher teacher = (Teacher) o; System.out.println(name + "得到作业信息:" + teacher.getContent()); } } }
/** * @Auther: zyx * @Date: 2018/8/6 10:35 */ public class Test { public static void main(String[] args) { /** * instance observable */ Teacher teacher = new Teacher(); Student s1 = new Student(teacher, "张三"); Student s2 = new Student(teacher, "李四"); Student s3 = new Student(teacher, "王五"); teacher.setHomework("第二页第六题"); teacher.setHomework("第三页第七题"); teacher.setHomework("第五页第八题"); } }
输出信息: