单例模式(C++实现)

(本博客旨在个人总结回顾)

1、详情:

单例模式:保证类仅有一个实例,并提供一个访问它的全局访问点。

分类:

懒汉式:类的实例在使用的使用才创建。(多线程使用双检锁解决线程安全问题)

饿汉式:类文件加载的时候创建实例,在没有使用类的情况下造成资源浪费。

特点与选择:

对于访问量比较大情况,采用饿汉式实现,可以实现更好的性能(获取实例时无需加锁),以空间换时间。

②对于访问量较小,采用懒汉式实现,以时间换空间。

懒汉式对应单例类:

(非线程安全)

备注:代码环境实在windows平台(个人博客所有例子如无特殊说明都在windows平台上开发的)

Singlenton.h

#pragma once
class Singlenton
{
private:
    Singlenton();
    ~Singlenton();

private:
    static Singlenton* m_pInstance;

public:
    static Singlenton* getInstance();
};

Singlenton.cpp

#include "stdafx.h"
#include "Singlenton.h"

Singlenton::Singlenton()
{
}

Singlenton::~Singlenton()
{
}

Singlenton* Singlenton::getInstance()
{
    if (NULL == m_pInstance)
    {
        m_pInstance = new Singlenton();
    }
    return m_pInstance;
}

Singlenton* Singlenton::m_pInstance = NULL;

(使用双检锁确保线程安全)

Singlenton.h

#pragma once
#include<windows.h>

class MyLock
{
public:
    MyLock() :m_criticalSection()
    {
        InitializeCriticalSection(&m_criticalSection);
    }
    ~MyLock()
    {
        DeleteCriticalSection(&m_criticalSection);
    }

public:
    void Lock()
    {
        EnterCriticalSection(&m_criticalSection);
    }
    void Unlock()
    {
        LeaveCriticalSection(&m_criticalSection);
    }

private:
    CRITICAL_SECTION m_criticalSection;
};

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

private:
    static MyLock m_mutex;
    static Singlenton* m_pInstance;
     
public:
    static Singlenton* getInstance();
};

Singlenton.cpp

#include "stdafx.h"
#include "Singlenton.h"

Singlenton::Singlenton()
{
}

Singlenton::~Singlenton()
{
}

Singlenton* Singlenton::getInstance()
{
    //使用双检锁确保线程安全
    if (NULL == m_pInstance)
    {
        //(第二次判断)避免多个线程同时进入此处时,创建多个实例
        m_mutex.Lock();
        if (NULL == m_pInstance)
        {
            m_pInstance = new Singlenton();
        }
        m_mutex.Unlock();
    }
    return m_pInstance;
}

MyLock Singlenton::m_mutex = MyLock();

Singlenton* Singlenton::m_pInstance = NULL;

饿汉式对应单例类:

Singlenton.h

#pragma once
//饿汉式
class Singlenton
{
private:
    Singlenton();
    ~Singlenton();

public:
    static Singlenton* getInstance();

private:
    static Singlenton* m_pInstance;
};

Singlenton.cpp

#include "stdafx.h"
#include "Singlenton.h"

Singlenton::Singlenton()
{
}

Singlenton::~Singlenton()
{
}

Singlenton* Singlenton::getInstance()
{
    return m_pInstance;
}

Singlenton* Singlenton::m_pInstance = new Singlenton();

2、UML类图:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值