参考来源:http://www.cnblogs.com/hnrainll/archive/2011/12/29/2305582.html
观察者模式 Observer Pattern
类别:行为型模式
思想:当一个对象(被观察者或目标)的状态发生改变时,所有依赖于它的对象(观察者)都会得到通知并更新自身的状态。
应用:Observer模式的最知名的应用是在MVC结构,Observer模式可以很好的应用在文档和图表程序的制作中。
实现原理:
被观察者或目标(subject)接口:
注册观察者:public void attach(Observer o);
删除观察者:public void detach(Observer o);
向所有观察者发布通知:public void notice();
观察者(observer)接口:
接收到通知后,更新:public void update();
实例:
Subject代码:
public interface Subject{
public void attach(Observer o);
public void detach(Observer o);
public void notice();
}
Observer代码:
public interface Observer{
public void update();
}
Teacher代码:
package observerPattern;
import java.util.ArrayList;
import java.util.List;
public class Teacher implements Subject {
private String phone;
private List<Observer> students;
public Teacher() {
phone = "";
students = new ArrayList<Observer>();
}
@Override
public void attach(Observer o) {
// TODO Auto-generated method stub
students.add(o);
}
@Override
public void detach(Observer o) {
// TODO Auto-generated method stub
students.remove(o);
}
@Override
public void notice() {
// TODO Auto-generated method stub
for(Observer student : students) {
student.update();
}
}
public void setPhone(String phone) {
this.phone = phone;
notice(); // 关键
}
public String getPhone() {
return this.phone;
}
Student代码:
package observerPattern;
public class Student implements Observer {
private String name;
private String phone;
private Teacher teacher;
public Student(String name, Teacher teacher) {
this.name = name;
this.teacher = teacher;
}
public void show() {
System.out.println("Name: " + this.name + " Teacher's Phone: " + this.phone);
}
@Override
public void update() {
// TODO Auto-generated method stub
phone = teacher.getPhone();
}
}
Client代码:
package observerPattern;
import java.util.ArrayList;
import java.util.List;
public class Client {
public static void main(String[] args) {
List<Student> students = new ArrayList<Student>();
Teacher teacher = new Teacher();
for(int i = 0; i < 5; i++) {
Student student = new Student("s" + i, teacher);
students.add(student);
teacher.attach(student);
}
teacher.setPhone("123456");
for(Student student : students) {
student.show();
}
teacher.setPhone("654321");
for(Student student : students) {
student.show();
}
}
}
网友评论