參考來源:http://www.cnblogs.com/hnrainll/archive/2011/12/29/2305582.html
觀察者模式 Observer Pattern
類別:行為型模式
思想:當一個對象(被觀察者或目標)的狀態(tài)發(fā)生改變時肋层,所有依賴于它的對象(觀察者)都會得到通知并更新自身的狀態(tài)季眷。
應(yīng)用:Observer模式的最知名的應(yīng)用是在MVC結(jié)構(gòu)唬血,Observer模式可以很好的應(yīng)用在文檔和圖表程序的制作中泥兰。
實現(xiàn)原理:
被觀察者或目標(subject)接口:
注冊觀察者:public void attach(Observer o);
刪除觀察者:public void detach(Observer o)纺蛆;
向所有觀察者發(fā)布通知: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(); // 關(guān)鍵
}
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();
}
}
}