首页 > 其他 > 详细

单例模式的实现(饿汉式和懒汉式)

时间:2017-11-18 18:30:58      阅读:195      评论:0      收藏:0      [点我收藏+]

1.懒汉模式。

class Singleton  
{  
private:  
    static Singleton* m_instance;  
    Singleton(){}  
public:  
    static Singleton* getInstance();  
};  
  
Singleton* Singleton::getInstance()  
{  
    if(NULL == m_instance)  
    {  
        Lock();//借用其它类来实现,如boost  
        if(NULL == m_instance)  
        {  
            m_instance = new Singleton;  
        }  
        UnLock();  
    }  
    return m_instance;  
}  

2. 饿汉式:

class singleton
{
protected:
    singleton()
    {}
private:
    static singleton* p;
public:
    static singleton* initance();
};
singleton* singleton::p = new singleton;
singleton* singleton::initance()
{
    return p;
}

饿汉式是线程安全的。

单例模式的实现(饿汉式和懒汉式)

原文:http://www.cnblogs.com/simplepaul/p/7857491.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!