C++设计模式之单例模式

2020-01-06 13:01:55刘景俊

** Date         : 2013/11/20
** Description  : More information, please go to http://www.easck.com/> */
 
#include <iostream>
using namespace std;
 
class Singleton
{
public:
    static Singleton *GetInstance()
    {
        if (m_Instance == NULL )
        {
            m_Instance = new Singleton ();
        }
        return m_Instance;
    }
 
    static void DestoryInstance()
    {
        if (m_Instance != NULL )
        {
            delete m_Instance;
            m_Instance = NULL ;
        }
    }
 
    // This is just a operation example
    int GetTest()
    {
        return m_Test;
    }
 
private:
    Singleton(){ m_Test = 10; }
    static Singleton *m_Instance;
    int m_Test;
};
 
Singleton *Singleton ::m_Instance = NULL;
 
int main(int argc , char *argv [])
{
    Singleton *singletonObj = Singleton ::GetInstance();
    cout<<singletonObj->GetTest()<<endl;
 
    Singleton ::DestoryInstance();
    return 0;
}

 

这是最简单,也是最普遍的实现方式,也是现在网上各个博客中记述的实现方式,但是,这种实现方式,有很多问题,比如:没有考虑到多线程的问题,在多线程的情况下,就可能创建多个Singleton实例,以下版本是改善的版本。

实现二:

 

复制代码
/*
** FileName     : SingletonPatternDemo2
** Author       : Jelly Young
** Date         : 2013/11/20
** Description  : More information, please go to http://www.easck.com/> */
 
#include <iostream>
using namespace std;