单例模式(Singleton Pattern)属于创建型模式,它提供了一种创建对象的最佳方式。 这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
注意: 1、单例类只能有一个实例。 2、单例类必须自己创建自己的唯一实例。 3、单例类必须给所有其他对象提供这一实例。
意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
主要解决:一个全局使用的类频繁地创建与销毁。
何时使用:当您想控制实例数目,节省系统资源的时候。
如何解决:判断系统是否已经有这个单例,如果有则返回,如果没有则创建。
关键代码:构造函数是私有的。 优点:
缺点:没有接口,不能继承,与单一职责原则冲突,一个类应该只关心内部逻辑,而不关心外面怎么样来实例化。
使用场景:
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
class Singleton{
public:
static Singleton* Instance();
protected:
Singleton();
private:
static Singleton* _instance;
};
#endif
#include<iostream>
#include"Singleton.h"
using namespace std;
Singleton* Singleton::_instance = 0;
Singleton::Singleton(){
cout << "Singleton" << endl;
}
Singleton* Singleton::Instance(){
if (_instance == 0){
_instance = new Singleton();
}
return _instance;
}
#include"Singleton.h"
#include<iostream>
using namespace std;
int main(){
Singleton* sln = Singleton::Instance();
system("pause");
return 0;
}
Singleton 不可以被实例化,因此我们将其构造函数声明为 protected 或者直接声明为 private。
class singleton{
private:
static singleton* instace = 0;
singleton(){};
public:
singleton* GetInstace(){
if (instace == 0){
instace = new singleton();
}
return instace;
}
};
这种方式是最基本的实现方式,这种实现最大的问题就是不支持多线程。
class singleton{
private:
static singleton* instace;
singleton(){};
mutex l;
public:
singleton* GetInstace(){
l.lock();
if (instace == nullptr){
instace = new singleton();
}
l.unlock();
return instace;
}
};
class singleton{
private:
singleton(){};
private:
static singleton* instace;
public:
static singleton* GetInstace(){
return instace;
}
};
singleton* singleton::instace = new singleton();
Singleton 模式经常和 Factory(AbstractFactory) 模式在一起使用, 因为系统中工厂对象一般来说只要一个,这里的工厂对象实现就是同时是一个Singleton 模式的实例,因为系统我们就只要一个工厂来创建对象就可以了。