Poco 观察者模式(Observer Pattern) 订阅和发布某个感兴趣的通知, Observer和Notification
flyfish
先写一个实例代码
#include "Poco/NotificationCenter.h"
#include "Poco/Notification.h"
#include "Poco/Observer.h"
#include "Poco/NObserver.h"
#include "Poco/AutoPtr.h"
#include <iostream>
using Poco::NotificationCenter;
using Poco::Notification;
using Poco::Observer;
using Poco::NObserver;
using Poco::AutoPtr;
class BaseNotification: public Notification
{
};
class FileReadableNotification: public BaseNotification
{};
class FileWritableNotification: public BaseNotification
{};
class FileTimeoutNotification: public BaseNotification
{};
class Target
{
public:
void handleBase(BaseNotification* pNf)
{
std::cout << "handleBase: " << pNf->name() << std::endl;
pNf->release();
}
void handleRead(const AutoPtr<FileReadableNotification>& pNf)
{
std::cout << "handleRead: " << pNf->name() << std::endl;
}
void handleWrite(const AutoPtr<FileWritableNotification>& pNf)
{
std::cout << "handleWrite: " << pNf->name() << std::endl;
}
};
int main(int argc, char** argv)
{
NotificationCenter nc;
Target target;
nc.addObserver(Observer<Target, BaseNotification>(target, &Target::handleBase));
nc.addObserver(NObserver<Target, FileReadableNotification>(target, &Target::handleRead));
nc.addObserver(NObserver<Target, FileWritableNotification>(target, &Target::handleWrite));
nc.postNotification(new BaseNotification);
nc.postNotification(new FileReadableNotification);
nc.postNotification(new FileWritableNotification);
nc.removeObserver(Observer<Target, BaseNotification>(target, &Target::handleBase));
nc.removeObserver(NObserver<Target, FileReadableNotification>(target, &Target::handleRead));
nc.removeObserver(NObserver<Target, FileWritableNotification>(target, &Target::handleWrite));
return 0;
}
Observer是plain pointer
NObserver是 smart pointer
普通指针
typedef void (C::*Callback)(N*);
智能指针
typedef AutoPtr<N> NotificationPtr;
typedef void (C::*Callback)(const NotificationPtr&);
普通指针和智能指针按照各自的使用方式使用
Target通过NotificationCenter
的addObserver()
方法订阅感兴趣的notification
Target通过NotificationCenter
的removeObserver()
方法取消订阅感兴趣的notification
例如本实例对FileReadableNotification
和FileWritableNotification
感兴趣,
对FileTimeoutNotification
这个notification不感兴趣,那就不订阅也不用取消订阅。
派送notification是由NotificationCenter
的postNotification()
方法进行派送
target只要订阅该notification,target就会收到notification
通知某个target发生了什么事。
依据Poco源码
C对应Target Class
N对应Notification Class
NObserver
template <class C, class N>
class NObserver: public AbstractObserver
{
public:
typedef AutoPtr<N> NotificationPtr;
typedef void (C::*Callback)(const NotificationPtr&);
NObserver(C& object, Callback method):
_pObject(&object),
_method(method)
{
}
NObserver(const NObserver& observer):
AbstractObserver(observer),
_pObject(observer._pObject),
_method(observer._method)
{
}
~NObserver()
{
}
......
private:
NObserver();
C* _pObject;
Callback _method;
mutable Poco::Mutex _mutex;
};
Observer
template <class C, class N>
class Observer: public AbstractObserver
{
public:
typedef void (C::*Callback)(N*);
Observer(C& object, Callback method):
_pObject(&object),
_method(method)
{
}
Observer(const Observer& observer):
AbstractObserver(observer),
_pObject(observer._pObject),
_method(observer._method)
{
}
~Observer()
{
}
......
private:
Observer();
C* _pObject;
Callback _method;
mutable Poco::Mutex _mutex;
};
NotificationCenter
class Foundation_API NotificationCenter
/// A NotificationCenter is essentially a notification dispatcher.
/// It notifies all observers of notifications meeting specific criteria.
/// This information is encapsulated in Notification objects.
/// Client objects register themselves with the notification center as observers of
/// specific notifications posted by other objects. When an event occurs, an object
/// posts an appropriate notification to the notification center. The notification
/// center invokes the registered method on each matching observer, passing the notification
/// as argument.
///
/// The order in which observers receive notifications is undefined.
/// It is possible for the posting object and the observing object to be the same.
/// The NotificationCenter delivers notifications to observers synchronously.
/// In other words the postNotification() method does not return until all observers have
/// received and processed the notification.
/// If an observer throws an exception while handling a notification, the NotificationCenter
/// stops dispatching the notification and postNotification() rethrows the exception.
///
/// In a multithreaded scenario, notifications are always delivered in the thread in which the
/// notification was posted, which may not be the same thread in which an observer registered itself.
///
/// The NotificationCenter class is basically a C++ implementation of the NSNotificationCenter class
/// found in Apple's Cocoa (or OpenStep).
///
/// While handling a notification, an observer can unregister itself from the notification center,
/// or it can register or unregister other observers. Observers added during a dispatch cycle
/// will not receive the current notification.
///
/// The method receiving the notification must be implemented as
/// void handleNotification(MyNotification* pNf);
/// The handler method gets co-ownership of the Notification object
/// and must release it when done. This is best done with an AutoPtr:
/// void MyClass::handleNotification(MyNotification* pNf)
/// {
/// AutoPtr<MyNotification> nf(pNf);
/// ...
/// }
///
/// Alternatively, the NObserver class template can be used to register a callback
/// method. In this case, the callback method receives the Notification in an
/// AutoPtr and thus does not have to deal with object ownership issues:
/// void MyClass::handleNotification(const AutoPtr<MyNotification>& pNf)
/// {
/// ...
/// }
{
public:
NotificationCenter();
/// Creates the NotificationCenter.
~NotificationCenter();
/// Destroys the NotificationCenter.
void addObserver(const AbstractObserver& observer);
/// Registers an observer with the NotificationCenter.
/// Usage:
/// Observer<MyClass, MyNotification> obs(*this, &MyClass::handleNotification);
/// notificationCenter.addObserver(obs);
///
/// Alternatively, the NObserver template class can be used instead of Observer.
void removeObserver(const AbstractObserver& observer);
/// Unregisters an observer with the NotificationCenter.
bool hasObserver(const AbstractObserver& observer) const;
/// Returns true if the observer is registered with this NotificationCenter.
void postNotification(Notification::Ptr pNotification);
/// Posts a notification to the NotificationCenter.
/// The NotificationCenter then delivers the notification
/// to all interested observers.
/// If an observer throws an exception, dispatching terminates
/// and the exception is rethrown to the caller.
/// Ownership of the notification object is claimed and the
/// notification is released before returning. Therefore,
/// a call like
/// notificationCenter.postNotification(new MyNotification);
/// does not result in a memory leak.
bool hasObservers() const;
/// Returns true iff there is at least one registered observer.
///
/// Can be used to improve performance if an expensive notification
/// shall only be created and posted if there are any observers.
std::size_t countObservers() const;
/// Returns the number of registered observers.
static NotificationCenter& defaultCenter();
/// Returns a reference to the default
/// NotificationCenter.
private:
typedef SharedPtr<AbstractObserver> AbstractObserverPtr;
typedef std::vector<AbstractObserverPtr> ObserverList;
ObserverList _observers;
mutable Mutex _mutex;
};