C++单例模式

在C++中,单例模式是一种确保一个类只有一个实例,并提供一个全局访问点来访问这个实例的设计模式。

单例模式中的饿汉式(Eager Initialization)和懒汉式(Lazy Initialization)是两种不同的实例化策略,它们在实例的创建时机、性能和线程安全性方面有所区别。

以下是一个单例模式的典型实现:

饿汉式(Eager Initialization)

  1. 实例创建时机

    • 在程序启动时或类加载时立即创建单例实例。
  2. 性能

    • 由于实例在程序开始时就已经创建,因此第一次调用 getInstance 方法时不需要进行任何同步操作,速度较快。
  3. 线程安全性

    • 饿汉式是线程安全的,因为实例在类加载时就已经创建,JVM(Java虚拟机)保证了类加载过程的线程安全性。
  4. 资源使用

    • 如果单例实例很大或者初始化过程很耗时,并且程序可能永远不使用这个实例,那么饿汉式可能会浪费资源。
  5. 实现

    • 通常通过静态常量实现。

在这种方法中,单例实例在程序开始时就被创建。

复制代码
class Singleton {
public:
    static Singleton& getInstance() {
        return instance;
    }

private:
    Singleton() {}
    static Singleton instance; // 静态常量
};

Singleton Singleton::instance; // 在程序启动时创建实例

懒汉式(Lazy Initialization)

  1. 实例创建时机

    • 在第一次调用 getInstance 方法时创建单例实例。
  2. 性能

    • 第一次调用 getInstance 时需要创建实例,可能会有一定的延迟,但如果实例很大或者初始化很耗时,那么这种方式可以延迟资源的使用,提高性能。
  3. 线程安全性

    • 基本的懒汉式实现不是线程安全的,因为在多线程环境中可能会有多个线程同时进入 if 判断并创建多个实例。
    • 为了保证线程安全,通常需要添加同步机制(如互斥锁),但这会降低性能。
  4. 资源使用

    • 懒汉式只在需要时创建实例,更加节省资源。
  5. 实现

    • 通常通过静态成员变量和同步代码块实现。
cpp 复制代码
class Singleton {
public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }

private:
    Singleton() {}
    static Singleton* instance; // 静态成员变量
};

Singleton* Singleton::instance = nullptr; // 初始时为空

为了使懒汉式线程安全,可以添加互斥锁:

cpp 复制代码
#include <mutex>

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

private:
    Singleton() {}
    static Singleton* instance; // 静态成员变量
    static std::mutex mutex_;  // 互斥锁
};

Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mutex_;

懒汉式使用示例

cpp 复制代码
Student* Student::instance_ = NULL;
Student Student::staticInstance;

class Student: public people
{
public:
    static Student * instance(){return instance_;};

private:

    Student ();
    virtual ~Student ();

    static Student * instance_;
    static Student staticInstance;

    Student (const Student &);
    Student & operator = (const Student &);
};
Student ::Student ():
{
    instance_ = &staticInstance;
}
相关推荐
fouryears_234172 小时前
Flutter InheritedWidget 详解:从生命周期到数据流动的完整解析
开发语言·flutter·客户端·dart
我好喜欢你~2 小时前
C#---StopWatch类
开发语言·c#
lifallen4 小时前
Java Stream sort算子实现:SortedOps
java·开发语言
IT毕设实战小研4 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
快乐的划水a4 小时前
组合模式及优化
c++·设计模式·组合模式
cui__OaO5 小时前
Linux软件编程--线程
linux·开发语言·线程·互斥锁·死锁·信号量·嵌入式学习
星星火柴9365 小时前
关于“双指针法“的总结
数据结构·c++·笔记·学习·算法
鱼鱼说测试6 小时前
Jenkins+Python自动化持续集成详细教程
开发语言·servlet·php
艾莉丝努力练剑6 小时前
【洛谷刷题】用C语言和C++做一些入门题,练习洛谷IDE模式:分支机构(一)
c语言·开发语言·数据结构·c++·学习·算法
CHEN5_026 小时前
【Java基础面试题】Java基础概念
java·开发语言