什么是观察者模式
定义对象间一种一对多的依赖关系,使得每当一个对象改变时,所有依赖于他的对象都会得到通知并被自动更新。
观察者模式在实际应用中非常的广泛,他的重要作用就是把观察者和被观察者解耦,使得彼此依赖更小。好比我们android开发中给listview设定的Adapter,如果我们改变数据并通知Adapter,则我们listview的所有目标item数据内容就会相应改变。
观察者模式的适用场景
- 可拆分的关联行为
- 事件多级触发
- 跨系统的消息交换,比如消息队列、事件总线
观察者模式用例
客户端可订阅服务器消息通知,服务器有新消息需要通知客户端,则客户端可收到服务器发布的消息。
UML类图(Obserable和Observer是jdk内置类型,我们不用关心实现)
Client类:
public class Client implements Observer{
private String name;
public Client(String name){
this.name = name;
}
@Override
public void update(Observable o, Object arg) {
System.out.println("你好,"+ name +",最新消息:"+arg);
}
}
Server类:
public class Server extends Observable{
public void postNews(String content){
setChanged();
notifyObservers(content);
}
}
测试类:
public class Test {
public static void main(String[] args) {
//服务器
Server server = new Server();
//多个观察者(客户端)
Client client1 = new Client("张三");
Client client2 = new Client("李四");
Client client3 = new Client("王五");
Client client4 = new Client("马六");
//将观察者注册到可观察列表
server.addObserver(client1);
server.addObserver(client2);
server.addObserver(client3);
server.addObserver(client4);
//网站更新,通知观察者
server.postNews("国家新规定,下个月基本工资涨1000!!!");
}
}
运行结果:
你好,马六,最新消息:国家新规定,下个月基本工资涨1000!!!
你好,王五,最新消息:国家新规定,下个月基本工资涨1000!!!
你好,李四,最新消息:国家新规定,下个月基本工资涨1000!!!
你好,张三,最新消息:国家新规定,下个月基本工资涨1000!!!
这里就结束了代码,非常简洁。我们使用的是jdk内部提供的类,由此可见观察者模式的地位是举足轻重的,我们可以看一下源代码:
Observer:
public interface Observer {
/**
* This method is called whenever the observed object is changed. An
* application calls an <tt>Observable</tt> object's
* <code>notifyObservers</code> method to have all the object's
* observers notified of the change.
*
* @param o the observable object.
* @param arg an argument passed to the <code>notifyObservers</code>
* method.
*/
void update(Observable o, Object arg);
}
Observable:
public class Observable {
private boolean changed = false;
private Vector<Observer> obs;
/** Construct an Observable with zero Observers. */
public Observable() {
obs = new Vector<>();
}
/**
* Adds an observer to the set of observers for this object, provided
* that it is not the same as some observer already in the set.
* The order in which notifications will be delivered to multiple
* observers is not specified. See the class comment.
*
* @param o an observer to be added.
* @throws NullPointerException if the parameter o is null.
*/
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 <CODE>null</CODE> 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
* <code>hasChanged</code> method, then notify all of its observers
* and then call the <code>clearChanged</code> method to
* indicate that this object has no longer changed.
* <p>
* Each observer has its <code>update</code> method called with two
* arguments: this observable object and <code>null</code>. In other
* words, this method is equivalent to:
* <blockquote><tt>
* notifyObservers(null)</tt></blockquote>
*
* @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
* <code>hasChanged</code> method, then notify all of its observers
* and then call the <code>clearChanged</code> method to indicate
* that this object has no longer changed.
* <p>
* Each observer has its <code>update</code> method called with two
* arguments: this observable object and the <code>arg</code> 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 <tt>Observable</tt> object as having been changed; the
* <tt>hasChanged</tt> method will now return <tt>true</tt>.
*/
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 <tt>hasChanged</tt> method will now return <tt>false</tt>.
* This method is called automatically by the
* <code>notifyObservers</code> 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 <code>true</code> if and only if the <code>setChanged</code>
* method has been called more recently than the
* <code>clearChanged</code> method on this object;
* <code>false</code> otherwise.
* @see java.util.Observable#clearChanged()
* @see java.util.Observable#setChanged()
*/
public synchronized boolean hasChanged() {
return changed;
}
/**
* Returns the number of observers of this <tt>Observable</tt> object.
*
* @return the number of observers of this object.
*/
public synchronized int countObservers() {
return obs.size();
}
}
代码注释说的很明白了,总结一下流程,Observer是抽象观察者角色,而Client是Observer的实现类,Server类继承了Observable类有了可观察的功能,Client订阅了Server的可观察对象,每当Server有更新时通过遍历观察者对象,然后给所有观察者发布更新的消息,也就是调用了update方法,这样实现了一对多的通知功能,在这个系统中,Client和Server的通信都是依赖于Observer和Observable这些抽象,没有直接耦合,保证系统高灵活性。
优点:耦合度低,应对业务变化灵活。
缺点:我们可以看到 synchronized字样,说明他是线程安全的,也就是同步执行,我们在效率方面,是按顺序通知观察者的,如果某个卡顿,则其后也就势必出现问题。应考虑采用异步方式优化。