JDK中的设计模式之观察者模式

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

JDK中的

java.util.Observer
java.util.Observable

实现了观察者模式

其中接口Observer定义了订阅者update消息接收接口

void update(Observable o, Object arg);

Observable类定义了订阅者订阅、取消和通知接口

    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 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); }

下面是一个JDK 观察者模式的一个简单应用,代码示例如下:

消费发布者

重载订阅、取消、通知接口,直接调用父类Observable相关接口

import java.util.Observable;
import java.util.Observer;
public class Publisher extends Observable {
    @Override
    public synchronized void addObserver(Observer o) {
        super.addObserver(o);
    }

    @Override
    public synchronized void deleteObserver(Observer o) {
        super.deleteObserver(o);
    }

    @Override
    public void notifyObservers(Object arg) {
        super.setChanged();
        super.notifyObservers(arg);
    }

    private String name;

    public Publisher(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

消息订阅者

重载消息接收update方法

import java.util.Observable;
import java.util.Observer;

public class Subscriber implements Observer {
    private String name;

    public Subscriber(String name) {
        this.name = name;
    }

    @Override
    public void update(Observable o, Object arg) {
        System.out.println(String.format("%s received message %s from %s", name, arg, o.toString()));
    }
}

测试调用

public class Main {
    public static void main(String[] args) {
        Subscriber s0 = new Subscriber("s0");
        Subscriber s1 = new Subscriber("s1");

        Publisher observer = new Publisher("北京气象台");
        observer.addObserver(s0);
        observer.addObserver(s1);
        observer.notifyObservers("明日大雨");

    }
}

执行结果

s1 received message 明日大雨 from 北京气象台
s0 received message 明日大雨 from 北京气象台

你可能感兴趣的:(综合,Java,设计模式,架构)