java高级—->Java观察者的原理

  观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化时,会通知所有观察者对象,让他们能够自动更新自己。今天我们通过模拟按钮的处理事件来深入Java观察者模式的学习。

目录导航

  1. Java观察者的简要说明
  2. Java的按钮点击案例
  3. 使用Java中的Observer来模拟按钮监听事件机制
  4. Java中的Observer原理的说明
  5. 使用自定义的Observer来过滤按钮监听事件
  6. 友情链接

Java观察者的简要说明

观察者模式所涉及的角色有:

  ● 抽象主题(Subject)角色:抽象主题角色把所有对观察者对象的引用保存在一个聚集(比如ArrayList对象)里,每个主题都可以有任何数量的观察者。抽象主题提供一个接口,可以增加和删除观察者对象,抽象主题角色又叫做抽象被观察者(Observable)角色。

  ● 具体主题(ConcreteSubject)角色:将有关状态存入具体观察者对象;在具体主题的内部状态改变时,给所有登记过的观察者发出通知。具体主题角色又叫做具体被观察者(Concrete Observable)角色。

  ● 抽象观察者(Observer)角色:为所有的具体观察者定义一个接口,在得到主题的通知时更新自己,这个接口叫做更新接口。

  ● 具体观察者(ConcreteObserver)角色:存储与主题的状态自恰的状态。具体观察者角色实现抽象观察者角色所要求的更新接口,以便使本身的状态与主题的状态 像协调。如果需要,具体观察者角色可以保持一个指向具体主题对象的引用。

Java的按钮点击案例

我们建立一个项目去开始今天的测试。项目结构如下:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAP4AAAG7CAIAAABsFr9tAAAgAElEQVR4nO2d+XcU1br3+++4P77rvbznvtx1zuvBBGyPHDyMehWEc5RRCKDtYVDXAoUwJUwJIag0Bq5MhkgCxBAJCLQMBiRcyEBDRCBgZ8AkCEk6HTKnk8Cp94furt61967q6qGmvZ/PquXqrto1RD5dvat6f+uxCQDAH36/32b0MQCAASRA/faOzn35JTm5RTm5RQcLSnp6+9ClTzp65m4riXMXAJBwEqC+c/+xlt/rfa2N7a2/Pbj3c86+fHTpI2/3+FX5cusCgFHEpX5rm2/ztpz7l7f01e0crPu8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YOz7nlE37e9l/kdHPLa+eWT2gpP3H3s9FNR//vze1/J9cl+ueUU6PYSafe8Jc2pVwLYA8CVCpJK90K7QJAlfqSw8TO3JRgLu1PDqwdjsBSPvnY34Uiqo/f4Ee65oVF2ciJttm9O3Iz9B68zH19tIcjkFsLr4uqL/0YBDFWfZX39U87xlZnvEZONzZNOe0YO9TztOzjUb4Lf/jpw1G9jxsSeHgqSfSjBc2Cwt+F9/WtiLHqq+TrqSMKZv+ZMs184eupIwRBqHa+f331n8+n/LHhTK7eB8fq6AHFv4s42VsM43/NVUnXkyaFSRCEzvo7zVdK/E+9Oh8YeiuSJVj9u+LBRGN4AEBPQH2AU0B9gFNAfYBTQH2AUxKgfntH5778kpzcopzcooMFJT29ktEHTzp65m4riXMXAJBw/H7//wfPqk2rQUEZzgAAAABJRU5ErkJggg==" alt="" />

demo很简单,点击button按钮,修改button上显示的文字

package com.huhx.frame;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;/** * writer: huhx */public class Jframe extends JFrame {    private JButton button;    public Jframe() {        button = new JButton("text");        add(button);        setVisible(true);        button.addActionListener(new ActionListener() {            @Override            public void actionPerformed(ActionEvent e) {                button.setText("world");            }        });    }    public static void main(String[] args) {        new Jframe();    }}

使用Java中的Observer来模拟按钮监听事件机制

  java中的内置观察者模式有两个类:一个是observable被观察者类,一个是observer观察者接口。大体上与自定义模式相同,我们编写程序时只需继承obervable类,具体实现observer接口就可以了。值得注意的是:调用notifyObservers()方法之前,必须先调用setChanged()方法。这是因为observable类中把 changed变量初始化为false,notifyObservers()方法会先检查该变量是否为true,如果不为ture,就不会调用 update()方法,这就要我们调用notifyObservers()之前,先用setChanged()方法将changed变量设置为true。

现在我们以上述例子为引子,使用Java中内置的Observer自己来模拟一个按钮监听事件的案例:

一、 创建一个继承obervable类的被观察者,在案例中也就是Button,类记为:MyButton

package com.huhx.observer;import java.util.Observable;import java.util.Observer;/** * @author huhx */public class MyButton extends Observable {    public void addListeners(Observer observer) {        addObserver(observer);    }    public void process(Object args) {        setChanged();        notifyObservers(args);    }    public void process() {        process(null);    }}

二、 创建几个观察这个按钮的观察者,其实就是按钮的监听事件:

模拟点击事件:

package com.huhx.observer;import java.util.Observable;import java.util.Observer;public class ClickObserver implements Observer {    @Override    public void update(Observable o, Object arg) {        if (arg != null) {            System.out.println("click: " + arg.toString());        } else {            System.out.println("click no arg");        }    }}

模拟按下事件:

package com.huhx.observer;import java.util.Observable;import java.util.Observer;public class PressObserver implements Observer {    @Override    public void update(Observable o, Object arg) {        if (arg != null) {            System.out.println("press: " + arg.toString());        } else {            System.out.println("press no arg");        }    }}

三、 然后我们写一个测试的类,用于模拟按钮的事件:这里的process方法模拟真实按钮的触发事件,通知所有的观察者。比如我们按下按钮。

package com.huhx.observer;import java.util.Observable;import java.util.Observer;public class PersonTest {    public static void main(String[] args) {        MyButton button = new MyButton();        button.addObserver(new ClickObserver());        button.addListeners(new Observer() {            @Override            public void update(Observable o, Object arg) {                System.out.println("observer");            }        });        button.process("huhx");    }}

五、 它的输出结果如下:

observerclick: huhx

Java中的Observer原理的说明

上述我们通过案例,来模拟了按钮的监听事件原理,现在我们通过源码来详细的分析它的运行过程:

一、 Observer是一个观察者可以实现的接口,它的文档说明如下:

A class can implement the Observer interface when it wants to be informed of changes in observable objects.

Observer中有一个update()方法:

void update(Observable o, Object arg); // Observable 是观察者  arg 是notifyObservers方法传入的参数

二、 Observable是一个被观察者继承的类,它的文档说明大致如下:

This class represents an observable object, or "data" in the model-view paradigm. It can be subclassed to represent an object that the application wants to have observed. 

Observable有几个重要的方法,我们简单的介绍一下:

void addObserver(Observer o)            // 加入观察者到Vetor中protected  void clearChanged()          // 设置change为falseint countObservers()                    // 返回Vetor中观察者的数量void deleteObserver(Observer o)         // 从Vetor中删除指定的观察者void deleteObservers()                  // 删除所有的观察者void notifyObservers()                  // 通知Vetor中的观察者void notifyObservers(Object arg)        // 通知Vetor中的观察者,带参数boolean hasChanged()                    // 判断是否发生改变protected  void setChanged()            // 设置changed为true

三、 接下来,我们结合上述的例子来分析Observer的原理:

当执行MyButton button = new MyButton(),由于MyButton是继承Observable,所以下述代码会执行。

private boolean changed = false;private Vector obs;public Observable() {    obs = new Vector();}

当执行button.addObserver(new ClickObserver()),把参数中的Observer存放在上述初始化的Vetor中(为了适应多线程,用的是Vetor)

public synchronized void addObserver(Observer o) {    if (o == null)        throw new NullPointerException();    if (!obs.contains(o)) {        obs.addElement(o);    }}

当执行button.process(“huhx”),如果被观察者发生了改变,就通知Vetor中的观察者去执行update方法。

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

使用自定义的Observer来过滤按钮监听事件

上述案例中,我们还无法做到对观察者的过滤通知,现在我们自己实现一个Observer,来对事件监听的事件过滤,更好的模拟按钮的事件机制。

一、 定义一个常量类,用于各种事件的标记:

package com.huhx.myobserver;/** * huhx 陈慧 */public class Event {    // 触发所有的Listener    public static final int ALL = -1;    // 触发内部定义的Listener    public static final int DEFAULT = 0;    public static final int CLICK = 1;    public static final int PRESS = 2;    public static final int DOWN = 3;    public static final int FOCUE = 4;}

二、 定义一个Listener接口,和Java内置的Observer作用类似,注意方法中的参数是MyObservable

package com.huhx.listener;import com.huhx.myobserver.MyObservable;public interface Listener {    void actionPerformed(MyObservable o, Object arg);}

三、 定义几个实现Listener的观察者,也就是事件:

模拟点击事件:

package com.huhx.listener;import com.huhx.myobserver.MyObservable;/** * 陈慧 * @author Linux * */public class ClickListener implements Listener {    @Override    public void actionPerformed(MyObservable o, Object arg) {        if (arg != null) {            System.out.println("click: " + arg);        } else {            System.out.println("click");        }    }}

模拟按下事件:

package com.huhx.listener;import com.huhx.myobserver.MyObservable;public class PressListener implements Listener {    @Override    public void actionPerformed(MyObservable o, Object arg) {        System.out.println("press");    }}

模拟定义在内部类中的事件:

package com.huhx.listener;import com.huhx.myobserver.MyObservable;public class DefaultListener implements Listener {    @Override    public void actionPerformed(MyObservable o, Object arg) {    }}

四、 定义一个类似于Observable类的自定义被观察者:

package com.huhx.myobserver;import java.util.Vector;import com.huhx.listener.ClickListener;import com.huhx.listener.Listener;import com.huhx.listener.PressListener;/** * * @author huhx * */public class MyObservable {    private boolean changed = false;    private Vector<Listener> obs;    Object[] arrLocal;    public MyObservable() {        obs = new Vector<>();    }    protected synchronized void clearChanged() {        changed = false;    }    public void notifyObserverByEvent(int event, Object args) {        synchronized (this) {            if (!changed)                return;            arrLocal = obs.toArray();            clearChanged();        }        notifyFixObserver(event, args);    }    private void notifyFixObserver(int event, Object args) {        Listener listener = null;        for (int i = arrLocal.length - 1; i >= 0; i--) {            listener = (Listener) arrLocal[i];            switch (event) {            case Event.PRESS:                if (listener instanceof PressListener)                    ((PressListener) listener).actionPerformed(this, args);                break;            case Event.CLICK:                if (listener instanceof ClickListener)                    ((ClickListener) listener).actionPerformed(this, args);                break;            case Event.DEFAULT:                if (listener instanceof Listener)                    listener.actionPerformed(this, args);                break;            case Event.ALL:                listener.actionPerformed(this, args);                break;            default:                break;            }        }    }    public void notifyObserverByEvent(int event) {        notifyObserverByEvent(event, null);    }    public void notifyObserverByEvent(Object args) {        notifyObserverByEvent(Event.ALL, args);    }    public synchronized void addListener(Listener listener) {        if (listener == null)            throw new NullPointerException();        if (!obs.contains(listener)) {            obs.addElement(listener);        }    }    protected synchronized void setChanged() {        changed = true;    }}

五、 为了简化Button的使用,我们仿造Java中的做法,先创建一个AbstractButton,用于处理共公的代码:

package com.huhx.myobserver;import com.huhx.listener.Listener;public class AbstractButton extends MyObservable {    public void addListeners(Listener listener) {        addListener(listener);    }    public void process(int source, Object args) {        setChanged();        switch (source) {        case Event.CLICK:            notifyObserverByEvent(Event.CLICK, args);            break;        case Event.PRESS:            notifyObserverByEvent(Event.PRESS, args);            break;        case Event.DEFAULT:            notifyObserverByEvent(Event.DEFAULT, args);            break;        case Event.ALL:            notifyObserverByEvent(Event.ALL, args);        default:            break;        }    }    public void process(int source) {        process(source, null);    }}

六、 创建一个被观察者,也就是我们的按钮Button

package com.huhx.myobserver;/** * * @author Linux * */public class MyButtton extends AbstractButton {}

七、 在测试中使用:

package com.huhx.myobserver;import com.huhx.listener.ClickListener;import com.huhx.listener.Listener;public class PersonTest {    public static void main(String[] args) {        MyButtton buttton = new MyButtton();        buttton.addListener(new Listener() {            @Override            public void actionPerformed(MyObservable observable, Object object) {                System.out.println("listener");                System.out.println(observable + ", object: " + object.toString());            }        });        buttton.addListener(new ClickListener());        buttton.process(Event.CLICK);//        buttton.process(Event.DEFAULT, "world");    }}

它的输出结果如下:

click: 陈慧

观察者模式的应用

一、观察者模式的优点

  • 观察者和被观察者之间是抽象耦合

  如此设计,则不管是增加观察者还是被观察者都非常容易扩展,而且在Java中都已经实现的抽象层级的定义,在系统扩展方面更是得心应手。

  • 建立一套触发机制

  根据单一职责原则,每个类的职责是单一的,那么怎么把各个单一的职责串联成真实世界的复杂的逻辑关系呢?比如,我们去打猎,打死了一只母鹿,母鹿有三个幼崽,因失去了母鹿而饿死,尸体又被两只秃鹰争抢,因分配不均,秃鹰开始斗殴,然后羸弱的秃鹰死掉,生存下来的秃鹰,则因此扩大了地盘……这就是一个触发机制,形成了一个触发链。观察者模式可以完美地实现这里的链条形式。

二、观察者模式的缺点

  观察者模式需要考虑一下开发效率和运行效率问题,一个被观察者,多个观察者,开发和调试就会比较复杂,而且在Java中消息的通知默认是顺序执行,一个观察者卡壳,会影响整体的执行效率。在这种情况下,一般考虑采用异步的方式。

  多级触发时的效率更是让人担忧,大家在设计时注意考虑。

三、观察者模式的使用场景

  • 关联行为场景。需要注意的是,关联行为是可拆分的,而不是“组合”关系。
  • 事件多级触发场景。
  • 跨系统的消息交换场景,如消息队列的处理机制。

友情链接