实现单例步骤:
1.构造函数私有化。
2.增加静态私有的当前类的指针变量。
3.提供静态对外接口,可以让用户获得单例对象。
单例 分为:
1.懒汉式
2.饿汉式
懒汉式
代码如下:
class Singleton_lazy
{
public:static Singleton_lazy *getInstance(){if (pSingleton == nullptr){pSingleton = new Singleton_lazy;}return pSingleton;}private:Singleton_lazy() {}static Singleton_lazy * pSingleton;
};Singleton_lazy * Singleton_lazy::pSingleton = nullptr;
饿汉式
代码如下:
#include <iostream>
using namespace std;class Singleton_hungry
{public:
static Singleton_hungry *getInstance(){return pSingleton;}private:Singleton_hungry(){cout << "我是饿汉式" << endl;}static Singleton_hungry * pSingleton;
};Singleton_hungry * Singleton_hungry::pSingleton = new Singleton_hungry;int main()
{cout << "main start" << endl;return 0;
}
测试结果:
测试是否为单例?
代码如下:
#include <iostream>
using namespace std;class Singleton_lazy
{
public:static Singleton_lazy *getInstance(){if (pSingleton == nullptr){pSingleton = new Singleton_lazy;}return pSingleton;}private:Singleton_lazy() {}static Singleton_lazy * pSingleton;
};Singleton_lazy * Singleton_lazy::pSingleton = nullptr;class Singleton_hungry
{
public:static Singleton_hungry *getInstance(){return pSingleton;}
private:Singleton_hungry(){}static Singleton_hungry * pSingleton;
};Singleton_hungry * Singleton_hungry::pSingleton = new Singleton_hungry;void test01()
{Singleton_lazy *p1 = Singleton_lazy::getInstance();Singleton_lazy *p2 = Singleton_lazy::getInstance();if (p1 == p2){cout << "两个指针指向同一块内存空间,是单例" << endl;}else{cout << "不是单例" << endl;}Singleton_hungry *p3 = Singleton_hungry::getInstance();Singleton_hungry *p4 = Singleton_hungry::getInstance();if (p3 == p4){cout << "两个指针指向同一块内存空间,是单例" << endl;}else{cout << "不是单例" << endl;}}int main()
{test01();return 0;
}
测试结果:
单例对象释放问题:
不需要考虑内存释放,只有一个对象,占的内存太小,不会造成内存泄漏。
单例碰到多线程:
懒汉式碰到多线程,是线程不安全的。
饿汉式碰到多线程,是线程安全的。