The singleton mode of the design mode (Singleton), taking C++ as an example, realizes log output.

        Hello everyone, I haven't updated for a long time, and today I will add the most basic design pattern for you: the singleton pattern. This singleton model is really a knot in my heart. I interviewed Jingdong algorithm post around the end of 2021. The interviewer asked me to write a singleton. What about hahahaha, remember everything is the best arrangement. This article briefly introduces the singleton mode and gives the singleton mode log implementation.

Table of contents

 1. A brief introduction to the singleton mode

1.1 Basic introduction

1.2 Singleton mode usage scenarios

Second, singleton mode to achieve logging (Singleton Logger)

3. Summary


 1. A brief introduction to the singleton mode

1.1 Basic introduction

        The singleton mode only guarantees that only one instance exists in a program, and provides a global access point to access the instance. In fact, only one class object in the singleton mode is allowed to exist. It is the opposite of the multithreading idea, in order to ensure the operation of resources. safety. For example, the log system needs to record time, if multi-threaded, it will be messy.

        The key to implementing the Singleton pattern is that the constructor needs to be made private to prevent external code from creating multiple instances. At the same time, you need to provide a static method to get the instance. This method will check whether an instance already exists, and return this instance if it exists, otherwise create a new instance and return it.

        The following is a simple C++ singleton pattern sample code:

class Singleton {
public:
  static Singleton* GetInstance() {
    if (instance_ == nullptr) {
      instance_ = new Singleton();
    }
    return instance_;
  }

  void DoSomething() {
    // ...
  }

private:
  Singleton() {
    // ...
  }

  static Singleton* instance_;
};

Singleton* Singleton::instance_ = nullptr;

1.2 Singleton mode usage scenarios

  1. Configuration Manager: In an application, configuration information may need to be accessed in multiple places, and these configuration information are usually read-only. Using the singleton mode can ensure that the configuration information is only loaded once, and at the same time provide a global access point to access the configuration information.
  2. Logger: In an application, log information may need to be recorded in multiple places, and there is usually only one logger. Using the singleton pattern can ensure that only one logger is created and provide a global access point to record log information.
  3. Database connection pool: In an application, there may be many places that need to connect to the database, and database connections are usually limited resources. The database connection pool can be implemented using the singleton mode, ensuring that the connection is only created once, and providing a global access point to obtain the connection.
  4. Counter: In an application, it may be necessary to count an event or operation, and there is usually only one of these counters. Using the singleton pattern can ensure that the counter is only created once, and provide a global access point to count.
  5. Cache manager: In an application, some data needs to be cached, and the capacity of the cached data is usually limited. The cache manager can be implemented using the singleton pattern, ensuring that the cache is only created once, and providing a global access point to access cached data.

Second, singleton mode to achieve logging (Singleton Logger)

#include <iostream>
#include <fstream>
#include <string>
#include <ctime>

using namespace std;

class Logger {
private:
    static Logger* instance;
    ofstream logFile;

    Logger() {
        string filename = "log.txt";
        logFile.open(filename.c_str(), ios::out | ios::app);
    }

public:
    static Logger* getInstance() {
        if (instance == NULL) {
            instance = new Logger();
        }
        return instance;
    }

    void log(string message) {
        time_t now = time(0);
        char* dt = ctime(&now);
        logFile << dt << ": " << message << endl;
    }
};

Logger* Logger::instance = NULL;

int main() {
    Logger* logger = Logger::getInstance();
    logger->log("Hello World!");
    return 0;
}

        In the above code, the Logger class has a private constructor and a private static member variable instance. The getInstance() function is a public static member function that returns a unique instance of the Logger class. If the instance does not exist, a new instance is created. The log() function is used to write a message to a log file.

        In the main function, we first obtain the Logger instance, and then call the log() function to record the log. Since the Logger class is a singleton mode, only one Logger instance will exist during the running of the program, so calling the log() function multiple times will record logs in the same file.

        Please note that since the singleton pattern may have problems in a multi-threaded environment, it needs to be processed thread-safely. In this example, we ignore the issue of thread safety and only provide an implementation in a single-threaded environment.

3. Summary

       The singleton mode is very hard and lonely, please treat the singleton mode well.

       Have a nice weekend sweetheart.

Guess you like

Origin blog.csdn.net/weixin_44120785/article/details/129627054