单例模式
通过单例模式的方法创建的类在当前进程中只有一个实例
#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <Windows.h>
using namespace std;
//单例
class Singleton
{
private:
Singleton(string n):name(n){}
string name;
static Singleton* single;
public:
static Singleton& getInstance()
{
if (single == NULL)
{
single = new Singleton("我是一个单例");
}
return *single;
}
string& getName()
{
return name;
}
};
//加载时,初始化静态变量(懒汉模式)
Singleton* Singleton::single = NULL;
int main()
{
cout << Singleton::getInstance().getName() << endl;
// Singleton a; 由于构造函数已经是 private 所以无法正常创建对象
system("pause");
return 1;
}
单例模式会阻止其他对象实例化其自己的单例对象的副本,从而确保所有对象都访问唯一实例。单例分为懒汉模式和饿汉模式,区别在于一个在被引用时才创建,一个在程序加载时就创建了。也就是我们的数据成员 static Singleton* single;换成 static Singleton single
懒汉和饿汉
饿汉虽然在程序加载时就创建,但也提前占用了内存资源。
懒汉虽然只有在第一次被引用时创建,但是要注意在多线程应用中,需要用双重锁定来解决多次创建单例的问题。