Java 观察者模式介绍及示例

Java 观察者模式介绍及示例

一、观察者模式简介

1.1概念

观察者模式(Observer Pattern) : 观察者模式又名 发布/订阅模式,属于行为模式,定义了对象中一对多的依赖关系,让多个观察者(Observer)观察同一主题(Subject) ,当这个主题发生变化时,会通知所有的观察者对象并被自动更新。

1.2 UML类图

请添加图片描述

  • Subject 抽象主题:被观察者,抽象主题会把所有观察者对象保存在一个集合中,每个主题都可以有任意数量的观察者,主题提供两个方法,可以增加和删除观察者对象。
  • Observer: 抽象观察者,观察者的抽象类,定义了一个更新接口,使得在得到主题更改时更新自己。
  • ConcreteSubject:具体的主题,具体的被观察者,在具体主题内部状态发生改变时通知给所有注册过的观察者对象
  • ConcreteObserver: 具体的观察者对象,实现抽象观察者的定义,使得在得到主题状态更改同志是更新自身。

二、观察者模式java示例

在我们生活中,公告,通知这类事件都可以适用发布/订阅的这种模式,像我们日程使用的qq群,微信群也是观察者模式的实例,这里我们就用微信群聊用代码实现观察者模式简单实现。

2.1 抽象观察者对象(Observer)
/**
 * @Description: 抽象观察者
 * @author: xy
 * @date: 2022年11月18日 11:53
 */
public interface Observer {

	/**
	 * 更新方法
	 * @param message
	 */
	void update(String message);
}

2.2 抽象主题
/**
 * @Description: 抽象主题
 * @author: xy
 * @date: 2022年11月18日 11:53
 */
public interface Subject {
	/**
	 * 增加订阅者
	 * @param observer
	 */
	void attach(Observer observer);
	/**
	 * 删除订阅者
	 * @param observer
	 */
	void detach(Observer observer);
	/**
	 * 通知订阅者更新消息
	 */
	void notify(String message);
}
2.3 微信用户(具体观察者)
/**
 * @Description: 微信用户(具体观察者)
 * @author: xy
 * @date: 2022年11月18日 12:10
 */
public class WxUser implements Observer{
	//用户名
	private String userName;

	WxUser(String userName){
		this.userName = userName;
	}
	@Override
	public void update(String message) {
		System.out.println("用户【"+this.userName+"】接收到消息:"+message);
	}
}

2.4 具体主题 (微信群聊)
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 微信群聊(具体主题)
 * @author: scott
 * @date: 2022年11月18日 12:06
 */
public class WechatGroupSubject implements Subject{

	//微信群聊中的用户 观察者
	private List<Observer> observerList = new ArrayList<>();

	/**
	 * 添加群聊用户
	 * @param observer
	 */
	@Override
	public void attach(Observer observer) {
		observerList.add(observer);
	}
	/**
	 * 删除群聊用户
	 * @param observer
	 */
	@Override
	public void detach(Observer observer) {
		observerList.remove(observer);
	}

	/**
	 * 通知所有用户
	 * @param message
	 */
	@Override
	public void notify(String message) {
		for (Observer observer : observerList) {
			observer.update(message);
		}
	}
}
2.5 运行测试
/**
 * @Description: 运行客户端
 * @author: xy
 * @date: 2022年11月18日 12:13
 */
public class RunClient {

	public static void main(String[] args) {
		//1.创建三个用户(观察者)
		WxUser zhangsan = new WxUser("zhangsan");
		WxUser lisi = new WxUser("lisi");
		WxUser wangwu = new WxUser("wangwu");
		//创建群聊 (主题),将三个用户添加到群聊中
		Subject wechatGroupSubject = new WechatGroupSubject();
		wechatGroupSubject.attach(zhangsan);
		wechatGroupSubject.attach(lisi);
		wechatGroupSubject.attach(wangwu);
		//通知所有用户
		wechatGroupSubject.notify("hello world");
		System.out.println("---------------------------------------");
		//把wangwu踢出群聊
		wechatGroupSubject.detach(wangwu);
		//通知其他用户
		wechatGroupSubject.notify("wangwu 被踢出群聊");
	}
}

测试结果如下

image-20221118122302867

三、观察者模式的优缺点

3.1优点
  1. 观察者和被观察者建立于一个抽象的藕合,当具体的观察者和被观察者更改时都不会对对方有影响,符合依赖倒置原则。 - 目标与观察者之间建立了一套触发机制
3.2缺点
  1. 如果一个被观察者有很多直接间接的观察者的话,通知到所有观察者会很耗时,一般通知都是顺序通知,一个发生卡顿会影响整体的效率
  2. 被观察者只知道目标观察者发生了变化,不能知道具体发生了什么变化
  3. 有可能会使用循环依赖,导致死循环系统崩溃

四、适用场景

  1. 一对多的应用场景,一个对象改变状态时需要其他对象同步更新
  2. 消息队列等

五、源码中的观察者模式

java util包下的订阅者模式的实现

5.1 observer (观察者)

提供update方法更新观察者

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);
}
5.2 Observable(被观察者)

有删除新增统计通知观察者等方法。

package java.util;

/**
 * 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.
 * <p>
 * The order in which notifications will be delivered is unspecified.
 * The default implementation provided in the Observable class will
 * notify Observers in the order in which they registered interest, but
 * subclasses may change this order, use no guaranteed order, deliver
 * notifications on separate threads, or may guarantee that their
 * subclass follows this order, as they choose.
 * <p>
 * Note that this notification mechanism has nothing to do with threads
 * and is completely separate from the <tt>wait</tt> and <tt>notify</tt>
 * mechanism of class <tt>Object</tt>.
 * <p>
 * When an observable object is newly created, its set of observers is
 * empty. Two observers are considered the same if and only if the
 * <tt>equals</tt> method returns true for them.
 *
 * @author  Chris Warth
 * @see     java.util.Observable#notifyObservers()
 * @see     java.util.Observable#notifyObservers(java.lang.Object)
 * @see     java.util.Observer
 * @see     java.util.Observer#update(java.util.Observable, java.lang.Object)
 * @since   JDK1.0
 */
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();
    }
}

阿里的druid,apache的poi中都有具体实现。

参考文章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值