'Differences between Singleton and global variable [duplicate]
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
Solution 1:[1]
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 a 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 the Singleton class.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ted Klein Bergman |
