ccplusplus.com
Learn C, C++ Concepts
Sunday, January 1, 2012
mediator pattern example
/******************************************************************* * File : mediator-pattern.cpp * Author : Saurabh Gupta * Description : mediator design pattern example c++ * CMediatorPattern binds different classes together, and * the individual classes communicate via the mediator, * never directly. In this example, CMessage::m_print() * calls CMediatorPattern, not CPrinter directly. * Date : PM 10:37 01 January 2012 * Source : http://www.ccplusplus.com/2011/07/design-pattern-guide-with-example-and.html * Note : *******************************************************************/ #include <iostream> #include <string> using namespace std; class CPrinter { public: void m_print(const string & str) const { cout << str << endl; } }; class CMessage { public: virtual ~CMessage() { } virtual void m_print(const class CMediatorPattern & mediator) const; }; class CMediatorPattern { private: const CPrinter & printer; const CMessage & message; public: CMediatorPattern(const CPrinter & pr, const CMessage & msg) : printer(pr), message(msg) { } void m_print() const { message.m_print(*this); } void m_print(const string & str) const { printer.m_print(str); } }; void CMessage::m_print(const CMediatorPattern & mediator) const { mediator.m_print("Hello world!"); } void helloworld(const CMediatorPattern & mediator) { mediator.m_print(); } int main() { CPrinter printer; CMessage message; helloworld(CMediatorPattern(printer,message)); return 0; } /* * OUTPUT * [sgupta@rhel55x86 mediator]$ c++ mediator-pattern.cpp -o mediator-pattern [sgupta@rhel55x86 mediator]$ ./mediator-pattern Hello world! [sgupta@rhel55x86 mediator]$ */
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