一文带你理解观察者模式

观察者模式是一种使用比较广泛的设计模式,它的最大优点就是解耦,在某些地方,也叫订阅发布模式。

定义

定义对象间一种一对多的关系,使得每当一个对象状态发生改变时,每一个依赖它的对象都能接收到通知并进行自动更新

场景

  1. 关联行为场景
  2. 事件多级触发场景
  3. 跨系统(跨线程,跨模块等)的消息交互场景。比如事件总线

角色

Subject

被观察者,也叫主题,该主题可以被订阅,并且主题发生改变时,会通知所有的订阅者

Observer

观察者,也叫订阅者,订阅者一般是抽象的接口,由需要订阅主题者自己实现。

Observer实现

观察者的实现,主题发生改变时,会通知观察者,观察者可以根据改变状态来进行对应处理措施

源码分析

java.util包下,有一个Observable类,该类就是一个观察者模式在JDK中的实现,它是一个主题类,对应的抽象订阅者类是Observer,下面看下对应的源码

/**
 * 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.
 * <p>
 * An observable object can have one or more observers. An observer
 * may be any object that implements interface <tt>Observer</tt>. After an
 * observable instance changes, an application calling the
 * <code>Observable</code>'s <code>notifyObservers</code> method
 * causes all of its observers to be notified of the change by a call
 * to their <code>update</code> method.
 */
public class Observable {
    private boolean changed = false;
    private Vector<Observer> obs;

    public Observable() {
        obs = new Vector<>();
    }

    /**
     * Adds an observer to the set of observers for this object, provided
     * that it is not the same as some observer already in the set.
     * The order in which notifications will be delivered to multiple
     * observers is not specified. See the class comment.
     */
    public synchronized void addObserver(Observer o) {
        if (o == null)
            throw new NullPointerException();
        if (!obs.contains(o)) {
            obs.addElement(o);
        }
    }

    /**
     * Deletes an observer from the set of observers of this object.
     */
    public synchronized void deleteObserver(Observer o) {
        obs.removeElement(o);
    }

    /**
     * If this object has changed, as indicated by the
     * <code>hasChanged</code> method, then notify all of its observers
     * and then call the <code>clearChanged</code> method to
     * indicate that this object has no longer changed.
     * <p>
     * Each observer has its <code>update</code> method called with two
     * arguments: this observable object and <code>null</code>. In other
     * words, this method is equivalent to:
     * <blockquote><tt>
     * notifyObservers(null)</tt></blockquote>
     */
    public void notifyObservers() {
        notifyObservers(null);
    }

    /**
     * If this object has changed, as indicated by the
     * <code>hasChanged</code> method, then notify all of its observers
     * and then call the <code>clearChanged</code> method to indicate
     * that this object has no longer changed.
     * <p>
     * Each observer has its <code>update</code> method called with two
     * arguments: this observable object and the <code>arg</code> argument.
     */
    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;
    }

    /**
     * Indicates that this object has no longer changed, or that it has
     * already notified all of its observers of its most recent change,
     * so that the <tt>hasChanged</tt> method will now return <tt>false</tt>.
     * This method is called automatically by the
     * <code>notifyObservers</code> methods.
     */
    protected synchronized void clearChanged() {
        changed = false;
    }

    public synchronized boolean hasChanged() {
        return changed;
    }
    
    public synchronized int countObservers() {
        return obs.size();
    }
}

由于篇幅的原因,删掉了部分注释的代码

该主题类中有几个比较重要的方法

addObserver

deleteObserver

notifyObservers

这几个方法主要对应添加订阅者,删除订阅者,通知所有订阅者的功能,这三个功能也是主题类不可或缺的。

然后再看一下成员变量

private Vector<Observer> obs;

这个同步向量是用来存储订阅者的引用,之所以用同步的数据结构,是为了多线程的访问安全。当然,单纯的Vector是无法实现绝对线程安全的(至于为什么,可以参考《深入理解jvm虚拟机》一书中的多线程一章),所以在添加和删除订阅者的方法头添加了同步互斥关键字,标记该方法是同步互斥的。

public synchronized void addObserver(Observer o)

当然还有一个抽象订阅者接口

/**
 * A class can implement the <code>Observer</code> interface when it
 * wants to be informed of changes in observable objects.
 */
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.
     */
    void update(Observable o, Object arg);
}

可以看到该接口只有一个抽象方法update,具体订阅者需要实现该方法,从而在主题发生改变时,进行相应的处理。

观察者模式使用的场景很多。比如登陆场景,将用户登录状态的改变及时通知给订阅者。下面以设备网络状态的改变,来实现动态修改网络图标的需求,这也是一种订阅发布的典型场景。

/**
 * 抽象订阅者
 */
public interface IObsever {

  /**
   * 订阅者抽象方法,接收主题状态改变
   */
  void change(int type);
}


/**
 * 具体订阅者
 */
public class ObserverImpl implements IObsever {
  @Override public void change(int type) {
    System.out.println("该更新网络显示图标了,类型为;" + type);
  }
}

/**
 * 订阅主题
 */
public class NetSubject {

  private int mCurrentType;

  // 订阅者列表
  private List<IObsever> obsevers = new ArrayList<>();

  public void addObsever(IObsever obsever) {
    obsevers.add(obsever);
  }

  public void delObserver(IObsever obsever) {
    obsevers.remove(obsever);
  }

  public void notifyObservers() {
    for (int i = 0; i < obsevers.size(); i++) {
      obsevers.get(i).change(mCurrentType);
    }
  }

  /**
   * 刷新网络状态后,接收到当前真实的网络状态,通知所有订阅者
   */
  public void receive(int type) {
    if (type != mCurrentType) {
      mCurrentType = type;
      notifyObservers();
    }
  }
}

上例中,没有对多线程场景进行处理,当调用NetSubjectreceive方法时,如果NetSubject的网络状态发生改变,则会通知所有的订阅者,调用他们的change方法。可以看到,所有依赖网络状态来切换显示图标的地方都跟NetSubject没有耦合关系,消息都是通过订阅发布的形式来传递的,这也是观察者模式最大的优点。

总结

观察者模式(订阅发布模式)最大的作用就是解耦,在实际项目中,运用也是非常频繁。比如常见的事件总线EventBus,安卓中的广播接收器,甚至ListView中也是用了观察者模式。掌握好这种设计模式,对于编码是非常重要的。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值