观察者模式

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

	public synchronized void deleteObserver(Observer o) {
		obs.removeElement(o);
	}

	
	public void notifyObservers() {
		notifyObservers(null);
	}

	public void notifyObservers(Object arg) {
	
		Object[] arrLocal;

		synchronized (this) {
			if (!changed)
				return;
			arrLocal = obs.toArray();
			clearChanged();
		}

		for (int i = arrLocal.length - 1; i >= 0; i--)
			((Observer) arrLocal[i]).update(this, arg);
	}

	
	public synchronized void deleteObservers() {
		obs.removeAllElements();
	}

	
	protected synchronized void setChanged() {
		changed = true;
	}

	
	protected synchronized void clearChanged() {
		changed = false;
	}

	public synchronized boolean hasChanged() {
		return changed;
	}

	public synchronized int countObservers() {
		return obs.size();
	}
}
 
public interface Observer {
	
    void update(Observable o, Object arg);
}

    上面是Java的观察者模式的工具类,对于想实现观察的类只要实现Observer即可,并在update里写自己的业务处理逻辑即可;被观察者则要继承Obserable类,通过addObserver方法把观察者加进来,也就是说被观察者是了解所有正在观察它的对象的。

你可能感兴趣的:(观察者模式)