您的位置:首页 > 编程语言 > Java开发

java观察者模式

2015-07-11 17:11 567 查看
简单地说,观察者模式定义了一个一对多的依赖关系,让一个或多个观察者对象监察一个主题对象。这样一个主题对象在状态上的变化能够通知所有的依赖于此对象的那些观察者对象,使这些观察者对象能够自动更新

观察者模式所涉及的角色有:

1.抽象主题(Subject)角色:抽象主题角色把所有对观察者对象的引用保存在一个聚集(比如ArrayList对象)里,每个主题都可以有任何数量的观察者。抽象主题提供一个接口,可以增加和删除观察者对象,抽象主题角色又叫做抽象被观察者(Observable)角色。

2.具体主题(ConcreteSubject)角色:将有关状态存入具体观察者对象;在具体主题的内部状态改变时,给所有登记过的观察者发出通知。具体主题角色又叫做具体被观察者(Concrete Observable)角色。

3.抽象观察者(Observer)角色:为所有的具体观察者定义一个接口,在得到主题的通知时更新自己,这个接口叫做更新接口。

4.具体观察者(ConcreteObserver)角色:存储与主题的状态自恰的状态。具体观察者角色实现抽象观察者角色所要求的更新接口,以便使本身的状态与主题的状态 像协调。如果需要,具体观察者角色可以保持一个指向具体主题对象的引用。

抽象主题角色类:

public abstract class Subject {
//存放观察者对象的list集合
private List<Observer> list = new ArrayList<Observer>();

/**
* 注册观察者对象
* @param observer Observer
*/
public void attach(Observer observer){
System.out.println("attach an observer");
list.add(observer);
}

/**
* 删除观察者对象
* @param observer Observer
*/
public void detach(Observer observer){
list.remove(observer);
}

/**
* 通知所有的注册者观察对象
* @param state
*/
public void nodifyObservers(String newState){
for(Observer observer :list){
observer.update(newState);
}
}
}


具体主题角色类:

public class ConcreteSubject extends Subject {
private String state;

public String getState(){
return state;
}
//状态发生改变,通知各个观察者
public void change(String newState){
state = newState;
System.out.println("主题状态为:"+state);
this.nodifyObservers(state);
}
}


抽象观察者角色类:

public interface Observer {
/**
* @param state  更新的状态
*/
public void update(String state);
}


具体观察者角色类:

public class ConcreteObserver implements Observer {
//观察者的状态
private String observerState;

@Override
public void update(String state) {
/**
* 更新观察者的状态,使其与目标的状态保持一致
*/
observerState = state;
System.out.println("状态为:"+observerState);
}
}


客户端:

public class Client {
public static void main(String[] args) {
//创建主题对象
ConcreteSubject subject = new ConcreteSubject();
//创建观察者对象
ConcreteObserver observer = new ConcreteObserver();
//将观察者对象登记到主题对象上
subject.attach(observer);
//改变主题对象的状态
subject.change("1");
}
}


运行结果如下:

attach an observer

主题状态为:1

状态为:1

推模型和拉模型

在观察者模式中,又分为推模型和拉模型两种方式。

1.推模型

主题对象向观察者推送主题的详细信息,不管观察者是否需要,推送的信息通常是主题对象的全部或部分数据。

2.拉模型

主题对象在通知观察者的时候,只传递少量信息。如果观察者需要更具体的信息,由观察者主动到主题对象中获取,相当于是观察者从主题对象中拉数据。一般这种模型的实现中,会把主题对象自身通过update()方法传递给观察者,这样在观察者需要获取数据的时候,就可以通过这个引用来获取了。

下面是一个拉模型的实例

拉模型通常都是把主题对象当做参数传递。

拉模型的抽象观察者类

public interface Observer {
/**
* 更新接口
* @param subject 主题对象
*/
public void update(Subject subject);
}


拉模型的具体观察者类

public class ConcreteObserver implements Observer {
//观察者的状态
private String observerState;
@Override
public void update(Subject subject) {
observerState = ((ConcreteSubject)subject).getState();
System.out.println("观察者的状态为:"+observerState);
}
}


拉模型的抽象主题类

拉模型的抽象主题类主要的改变是nodifyObservers()方法。在循环通知观察者的时候,也就是循环调用观察者的update()方法的时候,传入的参数不同了。

public abstract class Subject {

private List<Observer> list = new ArrayList<Observer>();
/**
* 注册观察者对象
* @param observer Observer
*/
public void attach(Observer observer){
list.add(observer);
System.out.println("Attached an observer");
}

/**
* 删除观察者对象
* @param observer Observer
*/
public void detach(Observer observer){
list.remove(observer);
}

/**
* 通知所有注册的观察者对象
*/
public void nodifyObservers(){
for(Observer observer : list){
observer.update(this);
}
}
}


拉模型的具体主题类

跟推模型相比,有一点变化,就是调用通知观察者的方法的时候,不需要传入参数了。

public class ConcreteSubject extends Subject{
private String state;

public String getState(){
return state;
}
public void change(String newState){
state = newState;
System.out.println("主题状态为:"+state);
//状态发生改变,通知各个观察者
this.nodifyObservers();
}
}


两种模式的比较

1.推模型是假定主题对象知道观察者需要的数据;而拉模型是主题对象不知道观察者具体需要什么数据,没有办法的情况下,干脆把自身传递给观察者,让观察者自己去按需要取值。

2.推模型可能会使得观察者对象难以复用,因为观察者的update()方法是按需要定义的参数,可能无法兼顾没有考虑到的使用情况。这就意味着出现新情况的时候,就可能提供新的update()方法,或者是干脆重新实现观察者;而拉模型就不会造成这样的情况,因为拉模型下,update()方法的参数是主题对象本身,这基本上是主题对象能传递的最大数据集合了,基本上可以适应各种情况的需要。

JAVA提供的对观察者模式的支持

在JAVA语言的java.util库里面,提供了一个Observable类以及一个Observer接口,构成JAVA语言对观察者模式的支持。

Observer接口

这个接口只定义了一个方法,即update()方法,当被观察者对象的状态发生变化时,被观察者对象的notifyObservers()方法就会调用这一方法。

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类

被观察者类都是java.util.Observable类的子类。java.util.Observable提供公开的方法支持观察者对象,这些方法中有两个对Observable的子类非常重要:一个是setChanged(),另一个是notifyObservers()。第一方法setChanged()被调用之后会设置一个内部标记变量,代表被观察者对象的状态发生了变化。第二个是notifyObservers(),这个方法被调用时,会调用所有登记过的观察者对象的update()方法,使这些观察者对象可以更新自己。

public class Observable {
private boolean changed = false;
private Vector obs;

/** Construct an Observable with zero Observers. */

public Observable() {
obs = new Vector();
}

/**
* @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();
}
}


使用JAVA对观察者模式的支持

在这个例子中,被观察对象叫做Watched;而观察者对象叫做Watcher。Watched对象继承自java.util.Observable类;而Watcher对象实现了java.util.Observer接口。另外有一个Test类扮演客户端角色。

被观察者Watched类源代码

public class Watched extends Observable {
private String data="";

public String getData(){
return data;
}

public void setData(String data){
if(!this.data.equals(data)){
this.data = data;
setChanged();
}
notifyObservers();
}
}


观察者类源代码

public class Watcher implements Observer {
public Watcher(Observable o){
o.addObserver(this);
}

@Override
public void update(Observable o, Object arg) {
System.out.println("状态发生改变:"+((Watched)o).getData());
}
}


测试类源代码

public class Test {
public static void main(String[] args) {
//创建被观察者对象
Watched watched = new Watched();
//创建观察者对象,并将被观察者对象登记
Watcher watcher = new Watcher(watched);
//给被观察者状态赋值
watched.setData("start");
watched.setData("run");
watched.setData("stop");
}
}


Test对象首先创建了Watched和Watcher对象。在创建Watcher对象时,将Watched对象作为参数传入;然后Test对象调用Watched对象的setData()方法,触发Watched对象的内部状态变化;Watched对象进而通知实现登记过的Watcher对象,也就是调用它的update()方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java观察者模式