• 源码中的设计模式-观察者模式


    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可实现观察者模式。
    收住自己的心 一步一个脚印 做好自己的事
  • 相关阅读:
    最常见VC++编译错误信息集合
    网站运营最全总结
    KdPrint/DbgPrint and UNICODE_STRING/ANSI_STRING
    poj 2155 matrix
    【hdu2955】 Robberies 01背包
    【hdu4570】Multi-bit Trie 区间DP
    2014 SCAU_ACM 暑期集训
    qpython 读入数据问题: EOF error with input / raw_input
    【转】Python version 2.7 required, which was not found in the registry
    华农正方系统 登录地址
  • 原文地址:https://www.cnblogs.com/GodMode/p/13852677.html
Copyright © 2020-2023  润新知