定义对象间一种一对多的依赖关系,使得每当一个对象改变状态,则所有依赖它的对象都会得到通知并自动更新。不好理解?打个比方,
比如你订了报纸,每天更新了就会通知你。报亭和用户们就是一对多的关系。
观察者模式主要由观察者和被观察者组成
Observer 观察者,接口
Observable 被观察者,类
当被观察者更新时,会通知观察者。
观察者模式主要实现是接口回调,我们来简单编写个观察者模式的Demo
观察者
public class Coder implements Observer {
public String name;
public Coder(String name) {
this.name=name;
}
@Override
public void update(Observable o, Object arg) {
System.out.println("HI,"+name+",更新了"+arg);
}
}
被观察者
public class AndroidDev extends Observable {
public void postNewPublication(String content) {
//设置标志位
setChanged();
//通知Observer
notifyObservers(content);
}
}
public class Test {
public static void main(String [] args){
System.out.println("123");
AndroidDev dev=new AndroidDev();
Coder coder1=new Coder("1");
Coder coder12=new Coder("2");
Coder coder13=new Coder("3");
dev.addObserver(coder1);
dev.addObserver(coder12);
dev.addObserver(coder13);
dev.postNewPublication("更新了Android8.0");
}
}
下面是运行结果
123
HI,3,更新了更新了Android8.0
HI,2,更新了更新了Android8.0
HI,1,更新了更新了Android8.0
程序员们订阅了Android开发者,当Android版本有更新的时候会通知所有订阅了的程序员。我们来看下Observer 和Observable 的源码。
Observer
public interface Observer {
/**
* This method is called whenever the observed object is changed. An
* application calls an Observable object's
* notifyObservers
method to have all the object's
* observers notified of the change.
*
* @param o the observable object.
* @param arg an argument passed to the notifyObservers
* method.
*/
void update(Observable o, Object arg);
}
是不是很简单,就一个update方法。在看下Observable 类
public class Observable {
private boolean changed = false;
private Vector obs;
/** Construct an Observable with zero Observers. */
public Observable() {
obs = new Vector<>();
}
public synchronized void addObserver(Observer o) {
if (o == null)
throw new NullPointerException();
if (!obs.contains(o)) {
obs.addElement(o);
}
}
/**
* Deletes an observer from the set of observers of this object.
* Passing null
to this method will have no effect.
* @param o the observer to be deleted.
*/
public synchronized void deleteObserver(Observer o) {
obs.removeElement(o);
}
/**
* If this object has changed, as indicated by the
* hasChanged
method, then notify all of its observers
* and then call the clearChanged
method to
* indicate that this object has no longer changed.
*
* Each observer has its update
method called with two
* arguments: this observable object and null
. In other
* words, this method is equivalent to:
*
* notifyObservers(null)
*
* @see java.util.Observable#clearChanged()
* @see java.util.Observable#hasChanged()
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void notifyObservers() {
notifyObservers(null);
}
/**
* If this object has changed, as indicated by the
* hasChanged
method, then notify all of its observers
* and then call the clearChanged
method to indicate
* that this object has no longer changed.
*
* Each observer has its update
method called with two
* arguments: this observable object and the arg
argument.
*
* @param arg any object.
* @see java.util.Observable#clearChanged()
* @see java.util.Observable#hasChanged()
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void notifyObservers(Object arg) {
/*
* a temporary array buffer, used as a snapshot of the state of
* current Observers.
*/
Object[] arrLocal;
synchronized (this) {
/* We don't want the Observer doing callbacks into
* arbitrary code while holding its own Monitor.
* The code where we extract each Observable from
* the Vector and store the state of the Observer
* needs synchronization, but notifying observers
* does not (should not). The worst result of any
* potential race-condition here is that:
* 1) a newly-added Observer will miss a
* notification in progress
* 2) a recently unregistered Observer will be
* wrongly notified when it doesn't care
*/
if (!changed)
return;
arrLocal = obs.toArray();
clearChanged();
}
for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);
}
/**
* Clears the observer list so that this object no longer has any observers.
*/
public synchronized void deleteObservers() {
obs.removeAllElements();
}
/**
* Marks this Observable object as having been changed; the
* hasChanged method will now return true.
*/
protected synchronized void setChanged() {
changed = true;
}
/**
* Indicates that this object has no longer changed, or that it has
* already notified all of its observers of its most recent change,
* so that the hasChanged method will now return false.
* This method is called automatically by the
* notifyObservers
methods.
*
* @see java.util.Observable#notifyObservers()
* @see java.util.Observable#notifyObservers(java.lang.Object)
*/
protected synchronized void clearChanged() {
changed = false;
}
/**
* Tests if this object has changed.
*
* @return true
if and only if the setChanged
* method has been called more recently than the
* clearChanged
method on this object;
* false
otherwise.
* @see java.util.Observable#clearChanged()
* @see java.util.Observable#setChanged()
*/
public synchronized boolean hasChanged() {
return changed;
}
/**
* Returns the number of observers of this Observable object.
*
* @return the number of observers of this object.
*/
public synchronized int countObservers() {
return obs.size();
}
setChanged():设置更新的标志位
addObserver():添加Observer对象
notifyObservers(Object arg) :遍历集合中的Observier,并通知更新。
这样看起来是不是容易多了,先写到这。。。