源码中的设计模式-观察者模式
package java.util; /** * A class can implement the <code>Observer</code> interface when it * wants to be informed of changes in observable objects. * * @author Chris Warth * @see java.util.Observable * @since JDK1.0 */ 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); }
public class Observable { private boolean changed = false; // 存放观察者 private Vector<Observer> obs; 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); } .... }
Observable中的方法都为线程安全的,继承该类结合Observer可实现观察者模式。
收住自己的心 一步一个脚印 做好自己的事