3

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


  • Don't remember SO user but someone told me that it safer in a multi-threaded context. - Papipone
  • 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

1 답변


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 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.


  • 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
  • Probably because prople are not familiar with the concept. - Usama Alvi
  • This is wrong. Are you sure that your implementation ensures that there will be always one instance? - kadina

Linked


Related

Latest