一、这是最简单,也是最普遍的实现方式
#include <iostream>
#include<stdio.h>
using namespace std;
class Singleton
{
public:
static Singleton *GetInstance()
{
if(m_Instance == NULL)
{
cout << "Create a Instance" << endl;
m_Instance = new Singleton();
}
return m_Instance;
}
static void DestroyInstance()
{
if(m_Instance != NULL)
{
delete m_Instance;
m_Instance = NULL;
}
}
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::DestroyInstance();
system("pause");
return 0;
}
但是,这种实现方式,有很多问题,比如:没有考虑到多线程的问题,在多线程的情况下,就可能创建多个Singleton实例,以下版本是改善的版本。
二、
进行大数据的操作,因为静态初始化在程序开始时,也就是进入主函数之前,由主线程以单线程方式完成了初始化,所以静态初始化实例保证了线程安全性。在性能要求比较高时,就可以使用这种方式,从而避免频繁的加锁和解锁造成的资源浪费。
#include <iostream>
#include<stdio.h>
using namespace std;
class Singleton
{
public:
static Singleton *GetInstance()
{
cout << "Create a Instance" << endl; //
return const_cast<Singleton*>(m_Instance);
}
static void DestroyInstance()
{
if(m_Instance != NULL)
{
delete m_Instance;
m_Instance = NULL;
}
}
int GetTest()
{
return m_Test;
}
private:
Singleton()
{
m_Test = 10;
}
static const Singleton *m_Instance; //
int m_Test;
};
const Singleton *Singleton::m_Instance = new Singleton(); //
int main(int argc, char *argv [])
{
Singleton *singletonObj = Singleton::GetInstance();
cout << singletonObj->GetTest() << endl;
Singleton::DestroyInstance();
system("pause");
return 0;
}