Singleton: How should it be used

后端 未结 24 1914
Happy的楠姐
Happy的楠姐 2020-11-22 04:57

Edit: From another question I provided an answer that has links to a lot of questions/answers about singletons: More info about singletons here:

So I have read th

相关标签:
24条回答
  • 2020-11-22 05:10

    The first example isn't thread safe - if two threads call getInstance at the same time, that static is going to be a PITA. Some form of mutex would help.

    0 讨论(0)
  • 2020-11-22 05:10

    Another implementation

    class Singleton
    {
    public:
        static Singleton& Instance()
        {
            // lazy initialize
            if (instance_ == NULL) instance_ = new Singleton();
    
            return *instance_;
        }
    
    private:
        Singleton() {};
    
        static Singleton *instance_;
    };
    
    0 讨论(0)
  • 2020-11-22 05:11

    One thing with patterns: don't generalize. They have all cases when they're useful, and when they fail.

    Singleton can be nasty when you have to test the code. You're generally stuck with one instance of the class, and can choose between opening up a door in constructor or some method to reset the state and so on.

    Other problem is that the Singleton in fact is nothing more than a global variable in disguise. When you have too much global shared state over your program, things tend to go back, we all know it.

    It may make dependency tracking harder. When everything depends on your Singleton, it's harder to change it, split to two, etc. You're generally stuck with it. This also hampers flexibility. Investigate some Dependency Injection framework to try to alleviate this issue.

    0 讨论(0)
  • 2020-11-22 05:12

    Anti-Usage:

    One major problem with excessive singleton usage is that the pattern prevents easy extension and swapping of alternate implementations. The class-name is hard coded wherever the singleton is used.

    0 讨论(0)
  • 2020-11-22 05:13

    I still don't get why a singleton has to be global.

    I was going to produce a singleton where I hid a database inside the class as a private constant static variable and make class functions that utilize the database without ever exposing the database to the user.

    I don't see why this functionality would be bad.

    0 讨论(0)
  • 2020-11-22 05:16

    Modern C++ Design by Alexandrescu has a thread-safe, inheritable generic singleton.

    For my 2p-worth, I think it's important to have defined lifetimes for your singletons (when it's absolutely necessary to use them). I normally don't let the static get() function instantiate anything, and leave set-up and destruction to some dedicated section of the main application. This helps highlight dependencies between singletons - but, as stressed above, it's best to just avoid them if possible.

    0 讨论(0)
提交回复
热议问题