在一些设计中,可能涉及到多个对象都对一个对象的数据变化很有兴趣,都希望跟踪它的数据变化,那么应用观察者模式之后,如果对象中的数据变化之后,它会通知那些与之登记过的对象,让被人及时了解。观察者模式的类图:
从GOF的书中定义来看,只要符合发布-订阅的模式即为观察者模式,而上述类图部分线条也不是必要的,实现不同就所有不同。主要的思想为i:多个观察者关注某一个具体的主题之后,只要主题更新消息了,自动将消息发布到各个观察者处,除非观察者已经退订消息了。
下面是java实现的程序:
package dai;
/**
* @author Roger
* 主题接口
*/
public interface Subject {
public void addObserver(Observer observer);
public void deleteObserver(Observer observer);
public void notifyObserver();
}
package dai;
public interface Observer {
public void hearTelephone(String heardMsg);
}
package dai;
public class ConcreateObserver1 implements Observer{
@Override
public void hearTelephone(String heardMsg) {
// TODO Auto-generated method stub
System.out.println("ConcreateObserver1 "+heardMsg);
}
}
package dai;
public class ConcreateObserver2 implements Observer{
@Override
public void hearTelephone(String heardMsg) {
// TODO Auto-generated method stub
System.out.println("ConcreateObserver2 "+heardMsg);
}
}
package dai;
import java.util.ArrayList;
public class ConcreateSubject implements Subject{
ArrayList<Observer> observers ;
boolean change;
String newMSG;
ConcreateSubject(){
observers = new ArrayList<Observer>();
change = false;
this.newMSG ="";
}
@Override
public void addObserver(Observer observer) {
// TODO Auto-generated method stub
this.observers.add(observer);
}
@Override
public void deleteObserver(Observer observer) {
// TODO Auto-generated method stub
this.observers.remove(observer);
}
@Override
public void notifyObserver() {
// TODO Auto-generated method stub
if (change) {
for (int i = 0; i < this.observers.size(); i++) {
this.observers.get(i).hearTelephone(this.newMSG);
}
this.change = false;
}
}
public void giveNewMsg(String newMSG){
this.newMSG = newMSG;
this.change = true;
this.notifyObserver();
}
}
测试的客户端程序:
package dai;
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ConcreateSubject subject = new ConcreateSubject();
Observer observer1 = new ConcreateObserver1();
Observer observer2 = new ConcreateObserver2();
subject.addObserver(observer1);
subject.addObserver(observer2);
subject.giveNewMsg("hello ,boy");
}
}