Singleton mode (c++ design mode)

Interviewer: Please talk about the singleton model


For a certain class of software system is concerned, only a very important example of such an operating system can only open a Task Manager window, if the mechanism is not applicable to the window object uniquely oriented, it will not produce a variety of Necessary trouble, so with the singleton mode, the singleton class has a private constructor to ensure that users cannot directly instantiate it through the new keyword

Model advantages

  • Provides controlled access to unique instances
  • Can save system resources
  • Allow a variable number of instances (multiple instances)

Model disadvantages

  • Difficulty in expansion
  • Singleton class is too heavy

Applicable environment

  • The system only needs one instance object, or only one object is allowed to be created because of resource consumption
  • A single instance of the client call class is only allowed to use one public access point

Singleton code

/*
 * @ Description: C++ Design Patterns___Singleton
 * @ version: v1.0
 * @ Author: WeissxJ
 */

#include<iostream>

class Singleton
{
    
    
    private:
        Singleton() {
    
    }
        static Singleton* instance;
        // ...

    public:
        //复制构造函数和赋值运算符(=)都定义为deleted
        //意味着这无法进行单例的复制
        Singleton(Singleton const& )=delete;
        Singleton& operator=(Singleton const&)=delete;

        static Singleton* get(){
    
    
            if(!instance)
                instance=new Singleton();
            return instance;
        }

        static void restart(){
    
    
            if(instance)
                delete instance;
        }

        void tell(){
    
    
            std::cout<<"This is Singleton."<<std::endl;
            // ...
        }
        //...
};

Singleton* Singleton::instance=nullptr;

int main(){
    
    
    Singleton::get()->tell();
    Singleton::restart();
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_43477024/article/details/111682712