zoukankan      html  css  js  c++  java
  • 观察者模式(Observer)

      观察者模式地原理其实和监听器一样,使用地关键在于搞清楚说明是观察者,什么是被观察者

        1.观察者相当于事件监听

        2.被观察者相当于事件源和事件

    /**
     * 观察者
     */
    public class Watcher implements 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>
         */
        @Override
        public void update(Observable o, Object arg) {
            if (arg.toString().equals("openWindow")) {
                System.out.println("打开窗口  --- "+ this.getClass());
            }
        }
    }
    

      

    /**
     * 被观察者
     */
    public class Watched extends Observable {
        
        @Override
        public void notifyObservers(Object arg) {
            /**
             * 为了避免并发冲突,设置了changed标志位 changed = true,当前线程可观察所有观察者,内部同步块会设置为false
             * 通知过程中,正在新注册和撤销地无法通知到
             */
            super.setChanged();
            /**
             * 事件触发,通知所有感兴趣地观察者
             */
            super.notifyObservers(arg);
        }
    }
    

      

    public class WatcherDome {
        public static void main(String[] args) {
            // 被观察者
            Watched watched = new Watched();
            // 观察者
            Watcher watcher = new Watcher();
            // 为被观察者 注入 观察者
            watched.addObserver(watcher);
            watched.addObserver(new Observer() {
                @Override
                public void update(Observable o, Object arg) {
                    if (arg.toString().equals("closeWindow")) {
                        System.out.println("关闭窗口  ---- " + this.getClass());
                    }
                }
            });
            watched.notifyObservers("openWindow");
            watched.notifyObservers("closeWindow");
    
        }
    }
    
    
    打开窗口  --- class com.example.desing_mode.observer.Watcher
    关闭窗口  ---- class com.example.desing_mode.observer.WatcherDome$1
    

      当一个对象发生改变时,把这种改变通知给其他对象,从而影响其他对象地行为。

      从实现和调用过程来看,观察者和监听器模式基本一样,基本都是这个逻辑事件源对象上发生操作,它将调用事件监听器地一个方法,并将事件对象传递过去,套用到观察者模式上面就是,当被观察者发生操作时,观察者将根据观察者所做出地操作进行对应的操作

  • 相关阅读:
    (转载)Linux系统中分离线程的使用
    (转载)Vim的几种模式介绍
    (转载)Linux下检查内存泄漏、系统性能的系列工具
    (转载)Linux 僵尸进程与孤儿进程
    (转载)valgrind,好东西,一般人我不告诉他~~ 选项
    (转载)Linux进程组、作业、会话的理解
    Open a file, and then readin a file tcl tk
    save vars and arrays
    itcl class example
    constructor with args tcl tk
  • 原文地址:https://www.cnblogs.com/huan30/p/12813420.html
Copyright © 2011-2022 走看看