6

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
Astronot
  • 61
  • 2
  • 9
  • Don't remember SO user but someone told me that it safer in a multi-threaded context. – Papipone Mar 18 '17 at 05:00
  • 2
    Also, if use global var, when the program starts, this object has to be initialized. If you use Singleton, then you can create it until the time that you are gonna use it for the first time. In the extreme situation, you don't have to use it until the program ends, so you don't have to create the Singleton at all. So using Singleton can let you create it only when you need it. Second, in the multi-thread program, if you just access the global var directly, it may cause problem which is hard to debug. – Jiahao Cai Mar 18 '17 at 05:00

1 Answers1

3

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.

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
M Usama Alvi
  • 187
  • 1
  • 15
  • You are absolutely correct about the original purpose of the Singleton pattern. But in most of the code I have seen, it is actually used as a replacement for a global variable. – Frank Puffer Mar 18 '17 at 11:04
  • Probably because prople are not familiar with the concept. – M Usama Alvi Mar 19 '17 at 17:26
  • 1
    This is wrong. Are you sure that your implementation ensures that there will be always one instance? – kadina Aug 14 '18 at 02:16
  • Since the Singleton object is static, that means there can only be one instance. – user8128167 Feb 07 '22 at 18:14
  • @kadina it can be made more ensure by making the constructor private. so it can't be instantiated by constructor but only static method – Elec Sep 09 '22 at 06:41