设计模式--单例模式(Singleton)【C++】

引言

在设计模式中,单例模式(Singleton Pattern)是一种非常常见且实用的模式。它的核心思想是确保一个类只有一个实例,并提供一个全局访问点。这种模式在需要全局唯一对象的场景中非常有用,比如配置管理、日志记录、数据库连接池等。

本文将通过一个简单的 C++ 示例,带你理解单例模式的基本概念和实现方法。即使你是设计模式的新手,也能轻松掌握!


什么是单例模式?

单例模式是一种创建型设计模式,它确保一个类只有一个实例,并提供一个全局访问点来获取该实例。它的主要特点包括:

  1. 唯一性:整个程序中只有一个实例存在。
  2. 全局访问:通过一个静态方法或变量来访问该实例。

单例模式的核心思想是通过控制类的实例化过程,避免外部代码随意创建多个实例。


为什么需要单例模式?

在某些场景中,我们需要确保一个类只有一个实例。例如:

  • 配置管理:程序的配置信息只需要加载一次,全局共享。
  • 日志记录:日志系统只需要一个实例来记录所有日志。
  • 数据库连接池:数据库连接池只需要一个实例来管理所有连接。

如果这些场景中允许多个实例存在,可能会导致资源浪费或数据不一致的问题。

C++实现单例模式

先从简单的单例模式入手,通过简单的锁机制实现单例

cpp 复制代码
#include <iostream>
#include <mutex>

class Singleton {
protected:
    Singleton() = default;//禁止外部构造
    Singleton(const Singleton&) = delete;//禁止外部拷贝构造
    ~Singleton() { std::cout << "~Singleton" << std::endl; }//禁止外部析构
    Singleton& operator=(const Singleton&) = delete;//禁止外部赋值
    static Singleton* _instance;//单例对象指针
    static std::mutex s_mutex; //互斥锁

public:
    //获取单例实例
    static Singleton* GetInstance() {//通过双重检查实现单例
        if (_instance == nullptr) {
            std::lock_guard<std::mutex> lock(s_mutex);//加锁
            if (_instance == nullptr) {
                _instance = new Singleton();//初始化单例对象
            }
        }
        return _instance;
    }
    //打印单例实例地址
    void PrintAddress() { std::cout << _instance << std::endl; }
};
//初始化静态成员变量
Singleton* Singleton::_instance = nullptr;
std::mutex Singleton::s_mutex;

int main() {
    Singleton* singleton1 = Singleton::GetInstance();
    singleton1->PrintAddress();
    Singleton* singleton2 = Singleton::GetInstance();
    singleton2->PrintAddress();
    std::cout << "Address: " << singleton1 << std::endl;
    std::cout << "Address: " << singleton2 << std::endl;
    return 0;
}

通过这个例子,你会发现singleton1和singleton2的地址相同

如果我们想通过单例模式来创建其他类实例,需要引入模板,参考下列代码。

假设我们需要创建一个Redis连接池,通过单例模式实现可以确保一个实例管理所有链接

cpp 复制代码
#include <iostream>
#include <memory>
#include <mutex>
class RedisConPool : public Singleton<RedisConPool>{
    friend class Singleton<RedisConPool>;//允许Singleton访问Redis的私有成员
private:
    Redis(){std::cout << "RedisConPool instance created!" << std::endl;}
    ~Redis(){std::cout << "RedisConPool instance destroyed!" << std::endl;}
};
template<typename T>
class Singleton {
protected:
    Singleton() = default;//禁止外部构造
    Singleton(const Singleton<T>&) = delete;//禁止外部拷贝构造
    ~Singleton() { std::cout << "~Singleton" << std::endl; }//禁止外部析构
    Singleton<T>& operator=(const Singleton<T>&) = delete;//禁止外部赋值
    static std::shared_ptr<T> _instance;//单例对象智能指针
    static std::once_flag s_flag;//保证单例对象只被初始化一次
public:
    //获取单例实例
    static std::shared_ptr<T> GetInstance() {
        std::claa_once(s_flag,[&]() {
            _instance = std::shared_ptr<T>(new T);//初始化单例对象
        });
        return _instance;
    }
    //打印单例实例地址
    void PrintAddress() { std::cout << _instance.get() << std::endl; }

};
//初始化静态成员变量
template<typename T>
std::shared_ptr<T> Singleton<T>::_instance = nullptr;
template<typename T>
std::once_flag Singleton<T>::s_flag;

int main() {
    //获取单例实例
    std::shared_ptr<RedisConPool> redis1 = Singleton<RedisConPool>::GetInstance();
    std::shared_ptr<RedisConPool> redis2 = Singleton<RedisConPool>::GetInstance();
    redis1->PrintAddress();
    redis2->PrintAddress();
    //比较两个单例实例的地址
    std::cout << "redis1 == redis2 ? " << (redis1 == redis2) << std::endl;
    return 0;
}

通过引入模板和智能指针单例类可以更方便的管理仅需一个实例的类

相关推荐
七月丶20 小时前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞20 小时前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼20 小时前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟2 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder2 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室2 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦3 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo6 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4966 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃6 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式