ccplusplus.com
Learn C, C++ Concepts
Saturday, October 1, 2011
singleton pattern example
/*********************************************************************** * File : singleton-pattern.cpp * Author : Saurabh Gupta * Desc : singleton pattern example * singleton pattern in c++ * Source : http://saurabhgupta0527.blogspot.com/2011/07/design-pattern-guide-with-example-and.html * Created : AM 10:38 01 October 2011 * Note : ************************************************************************/ #include <iostream> using namespace std; class Singleton { private: static bool instanceFlag; static Singleton *single; Singleton() { //private constructor } public: static Singleton* getInstance(); void method(); ~Singleton() { instanceFlag = false; } }; bool Singleton :: instanceFlag = false; Singleton* Singleton :: single = NULL; Singleton* Singleton :: getInstance() { if(! instanceFlag) { single = new Singleton(); instanceFlag = true; return single; } else { return single; } } void Singleton :: method() { cout << "Method of the singleton class" << endl; cout << "instanceFlag : " << instanceFlag << endl; } int main() { Singleton *sc1,*sc2; sc1 = Singleton::getInstance(); sc1->method(); sc2 = Singleton::getInstance(); sc2->method(); return 0; } /* * OUTPUT * [sgupta@rhel55x86 singleton]$ c++ singleton-pattern.cpp -o singleton-pattern [sgupta@rhel55x86 singleton]$ ./singleton-pattern Method of the singleton class instanceFlag : 1 Method of the singleton class instanceFlag : 1 [sgupta@rhel55x86 singleton]$ */
See Also:
Other Popular Design Pattern Implementation and Example Codes
3 comments:
Anonymous
September 20, 2012 at 11:08 AM
simple and clean example
Reply
Delete
Replies
Reply
Gaurav Sharma
March 1, 2014 at 11:10 PM
Good example
Reply
Delete
Replies
support@ccplusplus.com
March 2, 2014 at 10:14 AM
Thanks Gaurav
Delete
Replies
Reply
Reply
Add comment
Load more...
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
simple and clean example
ReplyDeleteGood example
ReplyDeleteThanks Gaurav
Delete