观察者设计模式及java Demo 发表于 2015-11-19 | 阅读数 观察者设计模式 1、主题对象管理着某些数据;2、当主题内的数据改变就会通知观察者(一旦数据发生改变,新的数据会以某种形式送到观察者手上);3、观察者已经订阅(注册)主题以便在主题数据改变时能够收到更新; 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108/** * @Title: ObserverTest.java * @Package com.primeton.test * @Description: TODO(用一句话描述该文件做什么) * @date 2015年11月6日 下午11:04:07 * @version V1.0 */package com.primeton.test;import java.util.Observable;import java.util.Observer;/** * @ClassName: ObserverTest * @Description: TODO(这里用一句话描述这个类的作用) * @author yuechang * @date 2015年11月6日 下午11:04:07 */public class Test { public static void main(String[] args) { School school = new School("娄底师专"); Student studentA = new Student(school.getSchoolName(), "A"); Student studentB = new Student(school.getSchoolName(), "B"); school.addObserver(studentA); school.addObserver(studentB); System.out.println(school); System.out.println(studentA); System.out.println(studentB); // 学校改名了 school.setSchoolName("湖南人文科技学院"); school.setChanged(); school.notifyObservers(school); System.out.println(school); System.out.println(studentA); System.out.println(studentB); }}class School extends Observable { private String schoolName; public School() { } /** * @param schoolName */ public School(String schoolName) { super(); this.schoolName = schoolName; } public String getSchoolName() { return schoolName; } public void setSchoolName(String schoolName) { this.schoolName = schoolName; } @Override public String toString() { return "School [schoolName=" + schoolName + "]"; } @Override protected synchronized void setChanged() { super.setChanged(); }}class Student implements Observer { private String studentName; private String schoolName; public Student() { } /** * @param studentName * @param schoolName */ public Student(String schoolName, String studentName) { super(); this.studentName = studentName; this.schoolName = schoolName; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getSchoolName() { return schoolName; } public void setSchoolName(String schoolName) { this.schoolName = schoolName; } @Override public void update(Observable o, Object arg) { if (arg instanceof School) { this.schoolName = ((School) arg).getSchoolName(); } } @Override public String toString() { return "Student [studentName=" + studentName + ", schoolName=" + schoolName + "]"; }}