观察者模式
观察者模式(Observer)参考博文(http://www.cnblogs.com/hnrainll/archive/2011/12/29/2305582.html)
基本概念:
观察者模式属于行为型模式,其意图是定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
思想:
(一)
建立目标(subject)与观察者(observer)接口:
目标(subject)接口:
建立一个注册观察者对象的接口; public void attach(Observer observer);
建立一个删除观察者对象的接口; public void detach(Observer observer);
建立一个当目标状态发生改变时,发布通知给观察者对象的接口; public void notice();
建立一个当收到目标通知后的更新接口: public void update();
老师有电话号码,学生需要知道老师的电话号码以便于在合时的时候拨打,在这样的组合中,老师就是一个被观察者
package observer;
public interface Subject {
public void attach(Observer observer);
public void detach(Observer observer);
public void notice();
}
package observer;
public interface Observer {
public void update();
}
Teacher需要实现Subject接口:
package observer;
import java.util.Vector;
public class Teacher implements Subject {
private Vector students;
private String num;
public Teacher(){
num="";
students=new Vector();
}
public Vector getVector(){
return students;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
notice();
}
public void attach(Observer observer) {
students.add(observer);
}
public void detach(Observer observer) {
students.remove(observer);
}
public void notice() {
for(int i=0;i<students.size();i++){
((Observer)students.get(i)).update();
}
}
}
Students需要实现Observer接口:
package observer;
public class Student implements Observer {
private String num;
private Teacher teacher;
private String name;
public Student(String name,Teacher teacher){
this.name=name;
this.teacher=teacher;
}
public void update() {
num=teacher.getNum();
}
public void show(){
System.out.println("name="+name+"\n"+"num="+num);
}
}
Client(客户端)代码测试:
package observer;
import java.util.Vector;
public class Client {
public static void main(String[] args) {
Teacher teacher=new Teacher();
Vector students=teacher.getVector();
for(int i=0;i<5;i++){
Student student=new Student("pokid"+i,teacher);
students.add(student);
teacher.attach(student);
}
teacher.setNum("2317321");
for(int i=0;i<5;i++){
((Student)students.get(i)).show();
}
}
}
测试结果: