This question already has an answer here:
I know that singleton allow only one instance of an object. Each method declared in the singleton will only operate on this object. I was wondering why to not simply declare a global object which will achieve the same goal?
I am certainly forgetting something. If singletons exist there must be specific uses or help to realize specific mechanisms.
For instance:
class Singleton
{
public:
static Singleton& Instance()
{
static Singleton sg;
return sg;
}
void function();
};
would be the same as:
class NotSingleton
{
public:
NotSingleon();
~NotSingleton()
void function();
};
NotSingleton nsg;
However, nothing prevent me to use more than one instance of NotSingleton
Singleton is used when we do not want to create more than one object. Singleton class ensures that not more than one object is created. However, having global object doesn't ensure this.
Class Singleton{
public static Singleton object==null;
public void singleton(){
if(object==null)
object = new Singleton();
return object;
}
}
This class will not create more than one object. This is the purpose of Singleton class.