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.
#include<stdio.h>
class singleton
{
public:
void print()
{
printf("hello\n");
}
int a;
}singleton;
int main()
{
//singleton s; #cannot define a new instant like this anymore.
singleton.a=5;
printf("a=%d\n",singleton.a);
singleton.print();
return 0;
}
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.
greate !!! very simple.
thank you so much for the simple explanation.
ehab
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!
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
How about declaring
class Singleton s; ??
wow!..nice simple…
well i think u had miskewed the concept of singleton .singleton is which gives the global point of access and avoiding the client accessing of copy constructors well which means u know the singleton definition.
Singletons are evil. It might be okay (and useful) for a Logger-class but apart from that I would highly avoid it. Few programmers use global variables in their programs since they make it very hard to keep the code modular, testable and thread safe. A singleton is just a storage for global variables with some code attached to it.
If you still want to use them I would rewrite your code as
#include
int a = 0;
void print()
{
printf(“hello\n”);
}
int main()
{
a = 5;
printf(“a=%d\n”, a);
print();
return 0;
}
since that is what it is