PureMVC PureMVC
|
00001 // Observer.hpp 00002 // PureMVC_C++ 00003 // 00004 // PureMVC Port to C++ by Tang Khai Phuong <phuong.tang@puremvc.org> 00005 // PureMVC - Copyright(c) 2006-2011 Futurescale, Inc., Some rights reserved. 00006 // Your reuse is governed by the Creative Commons Attribution 3.0 License 00007 // 00008 00009 #if !defined(__PUREMVC_PATTERNS_OBSERVER_OBSERVER_HPP__) 00010 #define __PUREMVC_PATTERNS_OBSERVER_OBSERVER_HPP__ 00011 00012 // STL include 00013 #include <stdexcept> 00014 #include <exception> 00015 // PureMVC include 00016 #if !defined(__PUREMVC_HPP__) 00017 #define __PUREMVC_INCLUDE__ 00018 #include "../PureMVC.hpp" 00019 #endif /* __PUREMVC_HPP__ */ 00020 00021 #include "../../Interfaces/IObserver.hpp" 00022 00023 #pragma pack(push) 00024 #pragma pack(4) 00025 00026 namespace PureMVC 00027 { 00028 namespace Patterns 00029 { 00030 using Interfaces::IObserver; 00031 00052 template<typename _Method, typename _Context> 00053 class Observer : public IObserver 00054 { 00055 private: 00056 Observer(void); 00057 public: 00061 explicit Observer(Observer const& arg) 00062 :IObserver() 00063 ,_notify_method(arg._notify_method) 00064 ,_notify_context(arg._notify_context) 00065 { } 00066 00067 public: 00078 explicit Observer(_Method notify_method, _Context* notify_context) 00079 :IObserver() 00080 ,_notify_method(notify_method) 00081 ,_notify_context(notify_context) 00082 ,_removed(false) 00083 { } 00084 00090 virtual void notifyObserver(INotification const& notification) 00091 { 00092 if (_notify_context == NULL) 00093 throw std::runtime_error("Notify context is null."); 00094 if (_notify_method == NULL) 00095 throw std::runtime_error("Notify method is null."); 00096 (*_notify_context.*_notify_method)(notification); 00097 } 00098 00105 virtual bool compareNotifyContext(void const* object) const 00106 { 00107 return _notify_context == object; 00108 } 00109 00113 Observer& operator=(Observer const& arg) 00114 { 00115 _notify_method = arg._notify_method; 00116 _notify_context = arg._notify_context; 00117 _removed = arg._removed; 00118 return *this; 00119 } 00120 00124 virtual ~Observer(void) 00125 { } 00126 private: 00127 _Method _notify_method; 00128 _Context* _notify_context; 00129 bool _removed; 00130 }; 00131 00132 template<typename _Method, typename _Context> 00133 IObserver* makeObserver(_Method notify_method, _Context* notify_context) 00134 { 00135 return new Observer<_Method, _Context>(notify_method, notify_context); 00136 } 00137 } 00138 } 00139 00140 #pragma pack(pop) 00141 00142 #endif /* __PUREMVC_PATTERNS_OBSERVER_OBSERVER_HPP__ */