• Singleton: A creative design pattern


  • Application Scenarios:

    1. Log system. If there should be only one logging system in a project, ensure that only one log object can be created.
    2. Global data store. The use of global variables should be avoided in C++. You can store data exclusively through a data class that has only one instantiation object, and other classes can store data that needs to be passed in it.
  • Implementation method:

    First, if you make the constructor of the class, the copy constructor, private, you cannot generate the class object from new outside the class. Then, a public interface is provided to get a unique instance of the class, through which only instantiated objects of the class can be obtained externally. Finally, through static variables in the public interface, ensure that the class is instantiated only once.

  • Advantages:

    Through the singleton mode, data transmission between classes can be realized without writing all kinds of communication interfaces between pairs, which reduces the complexity of code.

  • Disadvantages:

    The singleton pattern can be implemented in many modes, and the code demonstrated here does not take into account multithreading, where multiple instances may be generated. The improved singleton pattern will be updated below.


Here is a simple code implementation of the singleton pattern:
// Singleton.hpp
#include <iostream>
using namespace std;

// Log singleton class
class LogSingleton {
public:
    // Provide an interface to obtain a unique instance
    static LogSingleton* Instance(a) {
        if (NULL == m_pInstance) {
            // Instantiation objects are created only the first time this interface is called
            m_pInstance = new LogSingleton(a); }return m_pInstance;
    }

    // Displays the current log
    void Look(a) {
        printf("%s\n", strLog.c_str());
    }

    // Write to the log
    void Write(string strNew) {
        strLog += strNew;
    }
	
    // Memory reclamation
    ~LogSingleton() {
        if (NULL! = m_pInstance) {delete m_pInstance;
            m_pInstance = NULL; }}private:
    // Make the constructor and copy constructor private
    LogSingleton() {}
    LogSingleton(LogSingleton& oLog) {}

    static LogSingleton* m_pInstance; // A pointer to a unique instance
    string strLog;
};

// Remember to initialize the static pointer
LogSingleton* LogSingleton::m_pInstance = NULL;
Copy the code
Use in the main function
#include "Singleton.hpp"
int main(a)
{
	LogSingleton* pUserA = LogSingleton::Instance(a); pUserA->Write("Hello");

	LogSingleton* pUserB = LogSingleton::Instance(a); pUserB->Look(a);return 0;
}
Copy the code
Console output
Hello
Copy the code