C++11:参照Java Observable实现观察者模式

Posted 10km

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++11:参照Java Observable实现观察者模式相关的知识,希望对你有一定的参考价值。

Java中的观察者设计模式是个比较实用的设计模式,可以用于数据自动更新,但是C++中并没提供现成的类实现,于是我参照Java的 java.util.Observable,将java代码翻译为C++代码。自己实现了一个observable::observable,用法与Java的Observable类一样。

《JAVA设计模式之观察者模式》
https://www.cnblogs.com/porotin/p/7825656.html

实现代码

整个代码只有一个文件observable.hpp,java源码中的注释我也一并抄过来了。

/*
 * observable.hpp
 *  learning from java.util.Observable,java.util.Observer 
 *  Created on: 2021/09/15
 *      Author: guyadong
 */

#ifndef DTALK_OBSERVABLE_H_
#define DTALK_OBSERVABLE_H_
#include <memory>
#include <mutex>
#include <vector>
#include <algorithm>
namespace observable {
	class observable;
	/**
	 * A class can implement the <code>observer</code> interface when it
	 * wants to be informed of changes in observable objects.
	 * 对应 java.util.Observer 接口
	 */
	struct observer : public std::enable_shared_from_this<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.
		 */
		virtual void update(const observable &o, const std::shared_ptr<void>& arg) = 0;
	};
	using observer_ptr_type = std::shared_ptr<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.
	 * 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 is 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.
	 *
	 */
	class observable : public std::enable_shared_from_this<observable> {
	public:
		observable() = default;
		virtual ~observable() = default;
		/** 复制构造函数 */
		observable(const observable&o) 
		{
			obs = o.obs;
			changed = o.changed;
		}
		/** 赋值操作符 */
		observable& operator=(const observable&o) 
		{
			obs = o.obs;
			changed = o.changed;
			return *this;
		}
		/**
		 * 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 invalid_argument   if the parameter o is null.
		 */
		void addObserver(const observer_ptr_type& o) {
			std::lock_guard<std::mutex> guard(obs_mtx);
			if(!o)
			{
				throw std::invalid_argument("o is null");
			}
			auto found = std::find_if(obs.begin(), obs.end(), [&](const observer_ptr_type&e) { return o == e; });
			if (found == obs.end())
			{
				obs.emplace_back(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.
		 */
		void deleteObserver(const observer_ptr_type& o) {
			if (o) 
			{
				std::lock_guard<std::mutex> guard(obs_mtx);
				auto found = std::find_if(obs.begin(), obs.end(), [&](const observer_ptr_type&e) { return o == e; });
				obs.erase(found);
			}
		}
		/**
		 * 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>
		 *
		 */
		void notifyObservers() {
			notifyObservers(nullptr);
		}
		/**
		 * 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.
		 */
		void notifyObservers(const std::shared_ptr<void>& arg) {
			
			/*
			* a temporary array buffer, used as a snapshot of the state of
			* current Observers.
			*/
			decltype(obs) arrLocal;
			{
				std::lock_guard<std::mutex> guard(obs_mtx);
			
				if (!changed)
				{
					return;
				}
				arrLocal = obs;
				clearChanged();
			}
			for (observer_ptr_type e : obs)
			{
				e->update(*this, arg);
			}
		}

		/**
		 * Clears the observer list so that this object no longer has any observers.
		 */
		void deleteObservers() {
			std::lock_guard<std::mutex> guard(obs_mtx);
			obs.clear();
		}

		/**
		 * 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.
		 */
		bool hasChanged() const{
			return changed;
		}
		/**
		 * Returns the number of observers of this <tt>Observable</tt> object.
		 *
		 * @return  the number of observers of this object.
		 */
		int countObservers() const{
			return (int)obs.size();
		}
	protected:
		/**
		 * Marks this <tt>Observable</tt> object as having been changed; the
		 * <tt>hasChanged</tt> method will now return <tt>true</tt>.
		 */
		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.
		 *
		 */
		void clearChanged() {
			changed = false;
		}
	private:
		std::vector<observer_ptr_type> obs;
		/** std::mutex 作为 obs 字段的同步锁 */
		std::mutex obs_mtx;
		bool changed;
	};
} /* namespace observable */

#endif /* DTALK_OBSERVABLE_H_ */

说明

因为 std::mutex删除了复制构造函数和赋值操作符,所以这里为了允许observable 可以使用复制构造和赋值操作,必须实现复制构造函数和赋值操作符。

C++中没有接口,observable::observer是个只定义纯虚函数的类,对应 java.util.Observer 接口。

调用示例

以下为代码片段,用于示例观察者模式如何使用

#include <observable.hpp>
/**
 * OPTION 值改变观察者类(侦听器)
 * 当值改变时通知侦听器
 * 继承observable::observer实现update虚函数(接口方法)
 */
template<typename T>
struct ValueObserver : public observable::observer
{
	using value_listener_type = std::function<void(const T&)>;
	value_listener_type tmpl_listener;
	ValueObserver(const value_listener_type& tmpl_listener) :tmpl_listener(tmpl_listener) {}

	virtual void update(const observable::observable &, const std::shared_ptr<void>& arg) final
	{
		if (arg)
		{
			auto opt = std::static_pointer_cast<BaseOption>(arg);
			auto v = opt->getValue<T>();
			if (v && tmpl_listener)
			{
				tmpl_listener(static_cast<const T&>(*v));
			}
		}
	}
};
class BaseOption : public std::enable_shared_from_this<BaseOption >
{
	//************************************
	// 添加值改变侦听器
	// @param    const std::function<void(const T&)>& listener 侦听函数,为nullptr忽略
	// @return   dtalk::BaseOption& 当前对象
	//************************************
	template<typename T>
	BaseOption& addListener(const std::function<void(const T&)>& listener)
	{
		if (listener) {
			obs.addObserver(std::make_shared<ValueObserver<T>>(listener));
		}
		return *this;
	}
	dtalk::BaseOption& dtalk::BaseOption::setValue(const nlohmann::json & optionValue)
	{
		fields[__J_NAME(value)] = optionValue;
		/** 当值被修改时调用observable::notifyObservers函数通知所有的侦听器  */
		obs.notifyObservers(shared_from_this());
		return *this;
	}
private:
	/** 保存所有需要序列化的字段 */  
	nlohmann::json fields;
	/** observable 实例 */
	observable::observable obs;
}

以上是关于C++11:参照Java Observable实现观察者模式的主要内容,如果未能解决你的问题,请参考以下文章

利用Java提供的Observer接口和Observable类实现观察者模式

java中观察者模式Observable和Observer

[Java]_[初级]_[Observer和Observable失效后如何使用java.beans包下的类来实现观察者模式]

Java_观察者模式(Observable和Observer) -转

观察者设计模式

Observer,Observable实现观察者模式