c++单例模式实现

单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。下面是我的c++实现代码

Singleton.h

#pragma once
#include <afxmt.h>

class CSingleton{
    private:
        CSingleton();
        ~CSingleton();

      //把拷贝函数和复制函数私有化,防止被复制
        CSingleton(const CSingleton&);
        CSingleton& operator=(const CSingleton&);
        static CSingleton* pInstance;
        
    public:
         static CSingleton* getInstance();
         // other methods...
};

Singleton.cpp

#include "stdafx.h"
#include"Singleton.h"
static CCriticalSection mMutex;

//私有静态成员变量在使用前必须初始化
CSingleton* CSingleton::pInstance = NULL;
CSingleton::CSingleton(){
}
CSingleton::~CSingleton(){
      delete pInstance;
      pInstance = NULL;
 }
CSingleton::CSingleton(const CSingleton&)
{
}
CSingleton& CSingleton::operator=(const CSingleton&)
{
    return *this;
}
 CSingleton* CSingleton::getInstance(){
        if(pInstance == NULL){
            mMutex.Lock(); //多线程下保证对象唯一
             if (pInstance==NULL)
             {
                 pInstance = new CSingleton;
             }
            mMutex.Unlock();           
        }
   return pInstance;
}

main.cpp


#include "stdafx.h"
#include "Singleton.h"
#include <iostream>

#include<process.h>

using namespace std;

unsigned int __stdcall ThreadFunc1(void* param)
{
    CSingleton* pObject = (CSingleton*)param;
    cout<<pObject->a<<endl;
    pObject->a++;
    return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
    CSingleton* pSingLenton1 = CSingleton::getInstance();
    CSingleton* pSingLenton2 =  CSingleton::getInstance();

    CSingleton* pSingLenton3 =  CSingleton::getInstance();
    if (pSingLenton1==pSingLenton2)
    {
        cout <<"pSingLenton1==pSingLenton2"<<endl;
    }
    else
    {
        cout <<"pSingLenton1!=pSingLenton2"<<endl;
    }

    HANDLE hSaveThread1 =(HANDLE)_beginthreadex(0,0,ThreadFunc1,pSingLenton1,0,0);
    Sleep(1000);   //保证线程运行的顺序
    HANDLE hSaveThread2 =(HANDLE)_beginthreadex(0,0,ThreadFunc1,pSingLenton2,0,0);
    Sleep(1000);
    HANDLE hSaveThread3 =(HANDLE)_beginthreadex(0,0,ThreadFunc1,pSingLenton3,0,0);
    Sleep(5000); //让子线程执行完
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值