勿忘初心做自己 发表于 2025-11-4 20:42:16

单例模式 - 单例模式的实现与应用

弁言

单例模式(Singleton Pattern)是计划模式中最简朴且最常用的模式之一。它确保一个类只有一个实例,并提供一个全局访问点来访问该实例。单例模式常用于必要全局唯一对象的场景,如设置管理、日志记载、线程池等。
本文将详细先容单例模式的概念、实现方式以及在C++中的应用。
单例模式的概念

单例模式的核心头脑是确保一个类只有一个实例,并提供一个全局访问点。如许做的目标是为了克制多个实例之间的辩说,同时节省体系资源。
单例模式的长处


[*]全局唯一实例:确保一个类只有一个实例,克制多个实例之间的辩说。
[*]节省资源:由于只有一个实例,可以镌汰体系资源的斲丧。
[*]全局访问:提供一个全局访问点,方便其他对象访问该实例。
单例模式的缺点


[*]扩展性差:单例模式通常难以扩展,由于它的实例是全局唯一的。
[*]测试困难:由于单例模式的全局性,测试时大概会碰到困难。
[*]线程安全题目:在多线程情况下,单例模式的实现必要思量线程安全题目。
单例模式的实现

在C++中,单例模式的实现有多种方式,下面我们将先容几种常见的实现方式。
1. 懒汉式单例模式

懒汉式单例模式是指在第一次使用时才创建实例。这种方式可以节省资源,但必要思量线程安全题目。

class Singleton {
private:
    static Singleton* instance;
    Singleton() {}// 私有构造函数

public:
    static Singleton* getInstance() {
      if (instance == nullptr) {
            instance = new Singleton();
      }
      return instance;
    }
};

Singleton* Singleton::instance = nullptr;2. 饿汉式单例模式

饿汉式单例模式是指在步调启动时就创建实例。这种方式克制了线程安全题目,但大概会浪费资源。

class Singleton {
private:
    static Singleton* instance;
    Singleton() {}// 私有构造函数

public:
    static Singleton* getInstance() {
      return instance;
    }
};

Singleton* Singleton::instance = new Singleton();3. 线程安全的懒汉式单例模式

在多线程情况下,懒汉式单例模式必要思量线程安全题目。可以使用互斥锁(Mutex)来包管线程安全。

#include <mutex>

class Singleton {
private:
    static Singleton* instance;
    static std::mutex mtx;
    Singleton() {}// 私有构造函数

public:
    static Singleton* getInstance() {
      std::lock_guard<std::mutex> lock(mtx);
      if (instance == nullptr) {
            instance = new Singleton();
      }
      return instance;
    }
};

Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;4. 双重查抄锁定(Double-Checked Locking)

双重查抄锁定是一种优化后的线程安全单例模式,它镌汰了锁的使用次数,进步了性能。

#include <mutex>

class Singleton {
private:
    static Singleton* instance;
    static std::mutex mtx;
    Singleton() {}// 私有构造函数

public:
    static Singleton* getInstance() {
      if (instance == nullptr) {
            std::lock_guard<std::mutex> lock(mtx);
            if (instance == nullptr) {
                instance = new Singleton();
            }
      }
      return instance;
    }
};

Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;单例模式的应用

单例模式在实际开发中有广泛的应用,以下是一些常见的应用场景:
1. 设置管理

在应用步调中,通常必要一个全局的设置管理器来读取和存储设置信息。使用单例模式可以确保设置管理器只有一个实例,克制设置信息的辩说。

class ConfigManager {
private:
    static ConfigManager* instance;
    std::map<std::string, std::string> config;

    ConfigManager() {}// 私有构造函数

public:
    static ConfigManager* getInstance() {
      if (instance == nullptr) {
            instance = new ConfigManager();
      }
      return instance;
    }

    void setConfig(const std::string& key, const std::string& value) {
      config = value;
    }

    std::string getConfig(const std::string& key) {
      return config;
    }
};

ConfigManager* ConfigManager::instance = nullptr;2. 日志记载

日志记载器通常也必要一个全局唯一的实例,以确保全部的日志信息都写入同一个文件或输出流中。

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

    Logger() {
      logFile.open("log.txt", std::ios::app);
    }

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

    void log(const std::string& message) {
      logFile << message << std::endl;
    }

    ~Logger() {
      logFile.close();
    }
};

Logger* Logger::instance = nullptr;3. 线程池

线程池通常也必要一个全局唯一的实例,以管理全部的线程资源。

class ThreadPool {
private:
    static ThreadPool* instance;
    std::vector<std::thread> threads;

    ThreadPool() {}// 私有构造函数

public:
    static ThreadPool* getInstance() {
      if (instance == nullptr) {
            instance = new ThreadPool();
      }
      return instance;
    }

    void addThread(std::thread&& thread) {
      threads.push_back(std::move(thread));
    }

    void joinAll() {
      for (auto& thread : threads) {
            if (thread.joinable()) {
                thread.join();
            }
      }
    }
};

ThreadPool* ThreadPool::instance = nullptr;总结

单例模式是一种简朴但非常实用的计划模式,它确保一个类只有一个实例,并提供一个全局访问点。在C++中,单例模式的实现有多种方式,包罗懒汉式、饿汉式、线程安全的懒汉式以及双重查抄锁定。单例模式在设置管理、日志记载、线程池等场景中有广泛的应用。
盼望本文能资助你更好地明白单例模式的概念、实现方式以及应用场景。假如你有任何题目或发起,欢迎在品评区留言讨论。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 单例模式 - 单例模式的实现与应用