simple singleton class Posted on May 26th
Singleton is one of the common design pattern used to make a class object exist only one instant. I have read some books illustrate the implementation of singleton, I found it all complicated. I have tried to come out a very simple example on singleton class, bellow is my outcome.
With the class name and the object name appear the same, you make that class object singleton. Which means you can’t instantiate a new object using the name singleton anymore. The way to access the function and variables of a singleton object is direct.
This is my initial idea of how to make singleton simple.
Trackback URL
greate !!! very simple.
Commented Kfir on June 23rd, 2007.thank you so much for the simple explanation.
ehab
Commented ehab on June 25th, 2007.I’m pretty sure this will fail once you start working with projects that try to use this “singleton” in more than one CPP file. If you put the class in a header, and compile two CPPs that #include it, when you link them together you’ll have an object that is defined twice. Just a heads-up… Good idea though, and perfect for small jobs that need singletons!
Commented AC on December 5th, 2007.Hi All,
the code looks to be simple and working.
but have a doubt in the example.
i have written a class as for singleton as mentioned above in a new cpp file
from my main program i want to set the values(main.cpp) from the other cpp i want to access the values
how can i work out on this?
to be clear
singleton.cpp
class singleton
{
public:
int a;
char * strDSN;
}singleton;
main.cpp
#include “stdafx.h”
#include “singleton.cpp”
int _tmain(int argc, _TCHAR* argv[])
{
singletonclass.a = 5;
singletonclass.strDSN=”Test”;
return 0;
}
i have some other cpp where i need to get the value
config.cpp
class config
{
// I need to read the value here
}
Thanks
Srinivas
Commented Srinivas on December 7th, 2007.How about declaring
Commented Sunil on March 6th, 2008.class Singleton s; ??
[...] 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 [...]
Commented STL Singleton Template :: c/c++ linux programming by examples on July 5th, 2008.