ccplusplus.com
Learn C, C++ Concepts
Wednesday, January 4, 2012
observer design pattern c++ example
/*************************************************************************************** * File : observer-pattern.cpp * Author : Saurabh Gupta * Description : observer design pattern example c++ * : Observer is used to watch events on another object. * Here, the CWriterBoard class keeps an eye on the CMessageBoard class, * and writes the message each time CMessageBoard::m_post() is called. * Date : AM 09:13 04 january 2012 * Source : http://www.ccplusplus.com/2011/07/design-pattern-guide-with-example-and.html * Note : ***************************************************************************************/ #include <iostream> #include <string> class CObserverPattern { public: virtual ~CObserverPattern() { } virtual void m_OnMessage(const std::string &)=0; }; class CMessageBoard { private: CObserverPattern & observer; public: CMessageBoard(CObserverPattern & obs) : observer(obs) { } void m_post(const std::string & str) { observer.m_OnMessage(str); }; }; class CWriterBoard : public CObserverPattern { public: void m_OnMessage(const std::string & str) { std::cout << str << std::endl; } }; void display_message(CMessageBoard & msgb) { msgb.m_post("www.ccplusplus.com"); } int main() { CWriterBoard writer; CMessageBoard msgb(writer); display_message(msgb); return 0; } /* * OUTPUT * [sgupta@rhel6x64 observer]$ c++ observer-pattern.cpp -o observer-pattern [sgupta@rhel6x64 observer]$ ./observer-pattern www.ccplusplus.com [sgupta@rhel6x64 observer]$ */
See Also:
Design pattern Concept and Sample Codes
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment