单例主要是使用static修饰一个全局类对象,通过方法去创建类对象
1. 懒汉式,只有实例化时才创建类对象
2. 饿汉式,有没有实例化都会创建一个类对象
懒汉式单例
#include<iostream>
using namespace std;
class Singleton
{
public:
static Singleton *getInstance()
{
if(m_Singleton == NULL)
{
m_Singleton = new Singleton;
}
return m_Singleton;
}
static Singleton freeInstance()
{
if(m_Singleton != NULL)
{
delete m_Singleton;
m_Singleton = NULL;
cout << "Delete a singleton" << endl;
}
}
private:
Singleton()
{
cout << "Create a new singleton" << endl;
}
private:
static Singleton* m_Singleton;
};
Singleton* Singleton::m_Singleton = NULL;
int main()
{
Singleton * p1 = Singleton::getInstance();
Singleton * p2 = Singleton::getInstance();
if(p1 == p2)
{
cout << "THE SAME" << endl;
}
p1->freeInstance();
p2->freeInstance();
return 0;
}
饿汉式单例
#include<iostream>
using namespace std;
class Singleton
{
private:
Singleton()
{
cout << "Create a new singleton!" << endl;
}
static Singleton * m_Singleton;
public:
static Singleton * getInstance()
{
return m_Singleton;
}
static Singleton * freeInstance()
{
if(m_Singleton != NULL)
{
delete m_Singleton;
m_Singleton = NULL;
cout << "Delete a Singleton";
}
}
};
//相当于全局变量被初始化
Singleton * Singleton::m_Singleton = new Singleton;
int main()
{
Singleton *p1 = Singleton::getInstance();
Singleton *p2 = Singleton::getInstance();
if(p1 == p2)
{
cout << "THE SAME" << endl;
}
Singleton::freeInstance();
Singleton::freeInstance();
return 0;
}