设计模式 -(7)观察者模式/发布订阅模式(observer pattern)

设计模式 -(7)观察者模式/发布订阅模式(observer pattern)

前言

生活中有一些这样的例子:

  • 行人在过斑马线时会观察交通信号灯,当亮红灯时停止等待,当亮绿灯时过马路
  • 老师在黑白板书,学生在讲台下做笔记
  • 用户订阅某个公众号,当公众号发布消息时订阅的用户可以收到对应消息

在上面的例子中,信号灯可以理解为被观察者(observable),行人为观察者(observer),行人观察信号灯状态,状态改变时做出相应的行为反应,同样学生观察老师,当老师板书后,学生做笔记,观察者模式在生活中应用广泛,下面以公众号举例

举例说明

观察者接口:

/**
 * 观察者
 */
public interface Observer {
    /**
     * 接收来自被观察者的消息
     *
     * @param message
     */
    void receive(Observable observable, String message);
}

被观察接口:

/**
 * 被观察者
 */
public interface Observable {
    /**
     * 发布新消息时通知观察者
     * @param message
     */
    void notifyObserver(String message);

    String getName();
}

观察者实现类:

public class User implements Observer {

    private String name;

    public User(String name) {
        this.name = name;
    }

    @Override
    public void receive(Observable observable, String message) {
        System.out.println(name + " 收到来自'" + observable.getName() + "'的消息:" + message);
    }
}

被观察者实现类:

/**
 * 微信公众号
 */
public class WeChatOfficialAccounts implements Observable {

    private String name;

    private Set<Observer> observers = new HashSet<>();

    public WeChatOfficialAccounts(String name) {
        this.name = name;
    }

    // 添加观察者
    public WeChatOfficialAccounts addObserver(Observer observer) {
        if (!observers.contains(observer)) {
            observers.add(observer);
        }
        return this;
    }

    // 移除观察者
    public WeChatOfficialAccounts removeObserver(Observer observer) {
        if (observers.contains(observer)) {
            observers.remove(observer);
        }
        return this;
    }

    @Override
    public void notifyObserver(String message) {
        Iterator<Observer> iterator = observers.iterator();
        while (iterator.hasNext()) {
            Observer observer = iterator.next();
            observer.receive(this, message);
        }
    }

    @Override
    public String getName() {
        return name;
    }
}

测试:

public class Test {
    public static void main(String[] args) {
        // 被观察者 “阿斗归来了”
        WeChatOfficialAccounts aDou = new WeChatOfficialAccounts("阿斗归来了");

        // 被观察者 “程序员小灰”
        WeChatOfficialAccounts xiaoHui = new WeChatOfficialAccounts("程序员小灰");

        // 用户 张三 和 李四
        User zhangSan = new User("张三");
        User liSi = new User("李四");

        // 张三 和 李四 都关注了 “阿斗归来了”
        aDou.addObserver(zhangSan).addObserver(liSi);

        // “阿斗归来了” 发布消息
        aDou.notifyObserver("《南山的部长们》韩国最大胆电影");

        // 张三 关注了 “程序员小灰”
        xiaoHui.addObserver(zhangSan);

        // “程序员小灰” 发布消息
        xiaoHui.notifyObserver("Fastjson再曝反序列化漏洞,网友:Bugson又来了!");
    }
}
张三 收到来自'阿斗归来了'的消息:《南山的部长们》韩国最大胆电影
李四 收到来自'阿斗归来了'的消息:《南山的部长们》韩国最大胆电影
张三 收到来自'程序员小灰'的消息:Fastjson再曝反序列化漏洞,网友:Bugson又来了!

关于 观察者模式 的源码

JDK 源码:

观察者 java.util.Observer :

public interface Observer {
  
    void update(Observable o, Object arg);
}

被观察者 java.util.Observable :



package java.util;

public class Observable {
    private boolean changed = false;
    private Vector<Observer> obs;

    /** Construct an Observable with zero Observers. */

    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.
     *
     * @param   o   an observer to be added.
     * @throws NullPointerException   if the parameter o is null.
     */
    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.
     * Passing <CODE>null</CODE> to this method will have no effect.
     * @param   o   the observer to be deleted.
     */
    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>
     *
     * @see     java.util.Observable#clearChanged()
     * @see     java.util.Observable#hasChanged()
     * @see     java.util.Observer#update(java.util.Observable, java.lang.Object)
     */
    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.
     *
     * @param   arg   any object.
     * @see     java.util.Observable#clearChanged()
     * @see     java.util.Observable#hasChanged()
     * @see     java.util.Observer#update(java.util.Observable, java.lang.Object)
     */
    public void notifyObservers(Object arg) {
        /*
         * a temporary array buffer, used as a snapshot of the state of
         * current Observers.
         */
        Object[] arrLocal;

        synchronized (this) {
            /* We don't want the Observer doing callbacks into
             * arbitrary code while holding its own Monitor.
             * The code where we extract each Observable from
             * the Vector and store the state of the Observer
             * needs synchronization, but notifying observers
             * does not (should not).  The worst result of any
             * potential race-condition here is that:
             * 1) a newly-added Observer will miss a
             *   notification in progress
             * 2) a recently unregistered Observer will be
             *   wrongly notified when it doesn't care
             */
            if (!changed)
                return;
            arrLocal = obs.toArray();
            clearChanged();
        }

        for (int i = arrLocal.length-1; i>=0; i--)
            ((Observer)arrLocal[i]).update(this, arg);
    }

    /**
     * Clears the observer list so that this object no longer has any observers.
     */
    public synchronized void deleteObservers() {
        obs.removeAllElements();
    }

    /**
     * Marks this <tt>Observable</tt> object as having been changed; the
     * <tt>hasChanged</tt> method will now return <tt>true</tt>.
     */
    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.
     *
     * @see     java.util.Observable#notifyObservers()
     * @see     java.util.Observable#notifyObservers(java.lang.Object)
     */
    protected synchronized void clearChanged() {
        changed = false;
    }

    /**
     * Tests if this object has changed.
     *
     * @return  <code>true</code> if and only if the <code>setChanged</code>
     *          method has been called more recently than the
     *          <code>clearChanged</code> method on this object;
     *          <code>false</code> otherwise.
     * @see     java.util.Observable#clearChanged()
     * @see     java.util.Observable#setChanged()
     */
    public synchronized boolean hasChanged() {
        return changed;
    }

    /**
     * Returns the number of observers of this <tt>Observable</tt> object.
     *
     * @return  the number of observers of this object.
     */
    public synchronized int countObservers() {
        return obs.size();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值