ccplusplus.com
Learn C, C++ Concepts
Thursday, December 22, 2011
command design pattern example
/******************************************************************* * File : command-pattern.cpp * Author : Saurabh Gupta * Description : command design pattern in c++ * Date : PM 07:32 22 December 2011 * Source : http://www.ccplusplus.com/2011/07/design-pattern-guide-with-example-and.html * Note : ******************************************************************/ #include <vector> #include <algorithm> #include <iostream> class CCommandPattern { public: virtual ~CCommandPattern() { } virtual void m_execute()=0; }; class CDisplayHello : public CCommandPattern { public: void m_execute() { std::cout << "Hello "; } }; class CDisplayWorld : public CCommandPattern { public: void m_execute(){ std::cout << "world!" << std::endl; } }; class Commands { private: std::vector<CCommandPattern*> commands; struct ExecuteCommand { void operator()(CCommandPattern * cmd) { cmd->m_execute(); } }; public: void add_command(CCommandPattern & cmd){ commands.push_back(&cmd); } void m_execute() { std::for_each(commands.begin(), commands.end(), ExecuteCommand()); } }; void HelloWorld(Commands & commands) { commands.m_execute(); } int main(){ Commands commands; CDisplayHello hello; CDisplayWorld world; commands.add_command(hello); commands.add_command(world); HelloWorld(commands); return 0; } /* * OUTPUT * [sgupta@rhel6x64 command]$ c++ command-pattern.cpp -o command-pattern [sgupta@rhel6x64 command]$ ./command-pattern Hello world! [sgupta@rhel6x64 command]$ */
See Also:
Design Pattern Concepts and Example C++ Codes
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment