美文网首页工作生活
设计模式01 - 单例模式

设计模式01 - 单例模式

作者: 第八天的蝉啊 | 来源:发表于2019-07-02 15:47 被阅读0次
1. 定义:指一个类只有一个实例,且该类能自行创建这个实例的一种模式,特点如下
  • 单例类只有一个实例对象
  • 该单例对象必须由单例类自行创建
  • 单例类对外提供一个访问该单例的全局访问点
2. 懒汉式单例:类加载时没有生成单例,只有当第一次调用 getlnstance 方法时才去创建这个单例
  • 线程不安全的实现
//CSingleton.h
class CSingleton  
{  
public:  
    static CSingleton* GetInstance()  
    {
        if ( m_pInstance == NULL )
            m_pInstance = new CSingleton(); 
        return m_pInstance;  
    }  

protected:
    CSingleton() { }
    ~CSingleton() { }

private:  
    static CSingleton* m_pInstance;  
};

两个线程同时首次调用instance方法且同时检测到p是NULL值,则两个线程会同时构造一个实例给m_pInstance

  • 加锁的经典懒汉实现
//CSingleton.h
class CSingleton  
{
public:
    static pthread_mutex_t mutex;
    static CSingleton* GetInstance();

protected:
    CSingleton()
    {
        pthread_mutex_init(&mutex);
    }

private:
    static CSingleton* m_pInstance;
};

//CSingleton.cpp
pthread_mutex_t CSingleton::mutex;
CSingleton* CSingleton::m_pInstance = NULL;
CSingleton* CSingleton::GetInstance()
{
    if (m_pInstance  == NULL)
    {
        pthread_mutex_lock(&mutex);
        if (m_pInstance  == NULL)
            m_pInstance  = new CSingleton();
        pthread_mutex_unlock(&mutex);
    }
    return m_pInstance;
}
  • 内部静态变量的懒汉实现
class CSingleton  
{  
public:  
    static CSingleton* GetInstance()  
    {
        static CSingleton m_pInstance = CSingleton(); 
        return &m_pInstance; 
    }  

protected:
    CSingleton() { }
    ~CSingleton() { }
};
3. 饿汉式单例:类一旦加载就创建一个单例,保证在调用 getInstance 方法之前单例已经存在(线程安全)
//CSingleton.h
class CSingleton    
{    
public:    
    static CSingleton* GetInstance() { return m_CSingletonInstance; }  

protected:
  CSingleton() { }
  ~CSingleton() { }

private:
  static CSingleton* m_CSingletonInstance;
};

//CSingleton.cpp
CSingleton* CSingleton::m_CSingletonInstance = new CSingleton();

相关文章

  • python中OOP的单例

    目录 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 单例

    目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • python 单例

    仅用学习参考 目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计...

  • 单例模式Java篇

    单例设计模式- 饿汉式 单例设计模式 - 懒汉式 单例设计模式 - 懒汉式 - 多线程并发 单例设计模式 - 懒汉...

  • 设计模式 - 目录

    设计模式01 - 单例模式 设计模式02 - 工厂模式 设计模式03 - 建造者模式 设计模式04 - 适配器模式...

  • 设计模式 - 单例模式

    设计模式 - 单例模式 什么是单例模式 单例模式属于创建型模式,是设计模式中比较简单的模式。在单例模式中,单一的类...

  • 设计模式

    常用的设计模式有,单例设计模式、观察者设计模式、工厂设计模式、装饰设计模式、代理设计模式,模板设计模式等等。 单例...

  • 2018-04-08php实战设计模式

    一、单例模式 单例模式是最经典的设计模式之一,到底什么是单例?单例模式适用场景是什么?单例模式如何设计?php中单...

  • 基础设计模式:单例模式+工厂模式+注册树模式

    基础设计模式:单例模式+工厂模式+注册树模式 单例模式: 通过提供自身共享实例的访问,单例设计模式用于限制特定对象...

  • 单例模式

    JAVA设计模式之单例模式 十种常用的设计模式 概念: java中单例模式是一种常见的设计模式,单例模式的写法...

网友评论

    本文标题:设计模式01 - 单例模式

    本文链接:https://www.haomeiwen.com/subject/qsaacctx.html