单例设计模式

本文探讨了C++中两种实现单例模式的方法。第一种简单但不适用于多线程环境,可能会导致多个实例的创建。第二种通过静态初始化确保线程安全,适用于对性能要求较高的情况。代码示例展示了如何在C++中创建线程安全的单例对象,并提供了创建和销毁实例的静态方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单例模式

一、这是最简单,也是最普遍的实现方式

#include <iostream>
#include<stdio.h>
using namespace  std;

class Singleton
{
public:
    static Singleton *GetInstance()
    {
        if(m_Instance == NULL)
        {
            cout << "Create a Instance" << endl;
            m_Instance = new Singleton();
        }
        return m_Instance;
    }
    static void DestroyInstance()
    {
        if(m_Instance != NULL)
        {
            delete m_Instance;
            m_Instance = NULL;
        }    
    }
    int GetTest()
    {
        return m_Test;
    }

private:
    Singleton()
    {
        m_Test = 10;
    }
    static Singleton *m_Instance;
    int m_Test;
};

Singleton *Singleton::m_Instance = NULL;

int main(int argc, char *argv [])
{
	Singleton *singletonObj = Singleton::GetInstance();
    cout << singletonObj->GetTest() << endl;
    Singleton::DestroyInstance();
    system("pause");
    return 0;
}

在这里插入图片描述

但是,这种实现方式,有很多问题,比如:没有考虑到多线程的问题,在多线程的情况下,就可能创建多个Singleton实例,以下版本是改善的版本。

二、
进行大数据的操作,因为静态初始化在程序开始时,也就是进入主函数之前,由主线程以单线程方式完成了初始化,所以静态初始化实例保证了线程安全性。在性能要求比较高时,就可以使用这种方式,从而避免频繁的加锁和解锁造成的资源浪费。

#include <iostream>
#include<stdio.h>
using namespace  std;

class Singleton
{
public:
    static Singleton *GetInstance()
    {
        cout << "Create a Instance" << endl; //
        return const_cast<Singleton*>(m_Instance);
    }
    static void DestroyInstance()
    {
        if(m_Instance != NULL)
        {
            delete m_Instance;
            m_Instance = NULL;
        }    
    }
    int GetTest()
    {
        return m_Test;
    }

private:
    Singleton()
    {
        m_Test = 10;
    }
    static const Singleton *m_Instance; //
    int m_Test;
};

const Singleton *Singleton::m_Instance = new Singleton(); //

int main(int argc, char *argv [])
{
	Singleton *singletonObj = Singleton::GetInstance();
    cout << singletonObj->GetTest() << endl;
    Singleton::DestroyInstance();
    system("pause");
    return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值