单例模式模式(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;

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类图:

猜你喜欢

转载自blog.csdn.net/qq_23903863/article/details/91446846