STL Singleton Template Posted on June 9th
Singleton is one of my favorite design pattern, I use it to keep a global information for my application such as Configurations, Logger etc. I remember I wrote a post regarding simple singleton class, which it does not really work as singleton. It is just a silly way to make a object class looks like singleton.
Lately I’ll been using STL Singleton template for my projects, I find it simple to implement and yet efficient.
Lets define the Singleton Template:
In order to turn your own class into singleton, you class must inherits from CSingleton like this:
Access MyClass variables and functions like this:
I find the appearance of MyClass::Instance() are ugyl and lengthy, therefore I like to define a nicer look of singleton class.
#define MYCLASS MyClass::Instance()
So my source code looks cleaner.
Anyway, this is just my preference. Enjoy yourself with STL Singleton Template.
Trackback URL
I am guessing this is not a perfect singleton class.
As We can still do MyClass _myClass = new MyClass();
For a class to be singleton, we should make the constructor private. So that we can construct with a createInstance method.
That way, only one instance of class MyClass will be there in the app always.
0.02,
Commented Kartik on June 9th, 2008.Kartik
[...] Singleton Template Posted in June 8th, 2008 by in Uncategorized STL Singleton Template Singleton is one of my favorite design pattern, I use it to keep a global information for my [...]
Commented » STL Singleton Template A C One: What The World Is Saying About A C One on June 9th, 2008.Singleton can be implemented in another way as well. We shall declare a static variable in the class. Then in the constructor(which can be public), we will increment the static variable(which is our object instance). If we see the object count exceeding 1, then we can throw from the constructor. By this you can always new for only once from anywhere it is used, and it serves the rule of singleton.
Commented Subash on July 24th, 2008.