观察者模式是一种一对多的模式,"一"就是可观察的对象(observable or subject),"多"就是观察者(observer),当这个"一"发生改变的时候,会推送给所有的"多"。有点类似当今的微信公众号推送消息给所有的观众。观察者关心的是可观察对象的数据变动,可观察对象则负责通知观察者:Hey,有新消息了~
大体的原理是这样的: observable对象添加observer到自己的list中去,一旦消息达到可通知的地步,就会遍历list,通知list中的所有观察者。
这是实现的代码:
// 可观察对象
public abstract class Observable
{
ArrayList<Observer> observers = new ArrayList<Observer>();
boolean isChanged = false;
protected Object messageObj = null;
public Object getMessageObj() {
return messageObj;
}
public void setMessageObj(Object messageObj) {
this.messageObj = messageObj;
}
public void setChanged()
{
isChanged = true;
}
public void addObserver(Observer o)
{
observers.add(o);
}
public void removeObserver(Observer o)
{
int index = observers.indexOf(o);
if(index != -1)
{
observers.remove(index);
}
}
public void notifyObserver()
{
if(isChanged)
for (Observer o : observers){
o.update(this,messageObj);
}
}
}
// 具体的可观察对象
public class WeatherData extends Observable
{
public void pushNews()
{
System.out.println("push news to observers");
this.setMessageObj("It's a emergency case");
this.setChanged();
this.notifyObserver();
}
}
// 观察者
public interface Observer {
public void update(Observable o,Object obj);
}
//具体观察者
public class Client1 implements Observer{
Observable observable;
public Client1(Observable o){
this.observable = o;
this.observable.addObserver(this);
}
@Override
public void update(Observable o, Object obj) {
System.out.println("client1,message: "+obj.toString());
}
}
// 具体观察者
public class Client2 implements Observer{
Observable observable;
public Client2(Observable o){
this.observable = o;
this.observable.addObserver(this);
}
@Override
public void update(Observable o, Object obj) {
System.out.println("client2,message: "+obj.toString());
}
}
// 测试类
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
WeatherData data = new WeatherData();
Client1 client1 = new Client1(data);
Client2 client2 = new Client2(data);
data.pushNews();
}
}
下面是输出结果: