单例模式:
单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。
#include <iostream>
using namespace std;
class singleton{
private:
singleton(){};
static singleton* Inst;
public:
static singleton* getIns(){
if(NULL == Inst){ // 不适合多进程,如果某个线程在还未执行Inst = new singleton()时候,另外一个线程已经进来了,此时Inst还是NULL,就不能保证只有一个实例了
Inst = new singleton();
printf("this is called\n");
}
return Inst;
}
};
singleton* singleton::Inst = NULL;
int main(){
singleton *ins = singleton::getIns();
system("pause");
}
多线程版本1:参加《剑指offer》
#include <iostream>
using namespace std;
class singleton{
private:
singleton(){};
static singleton* Inst;
public:
static singleton* getIns(){
lock();
if(NULL == Inst){ // 得到锁后,只有当实例为空时,才会去创建,否则解锁并返回
Inst = new singleton();
printf("this is called\n");
}
unlock();
return Inst;
}
};
singleton* singleton::Inst = NULL;
int main(){
singleton *ins = singleton::getIns();
system("pause");
}
由于每次都加锁,使用锁的成本很高,只有在当前实例为空时才会去加锁,所以有了多线程版本2:
#include <iostream>
using namespace std;
class singleton{
private:
singleton(){};
static singleton* Inst;
public:
static singleton* getIns(){
if(NULL == Inst){ // 只有当实例为空时,才会去创建实例,别的线程已经创建完成时,那么直接返回即可/*也有成为延迟初始策略*/
lock();
if(NULL == Inst){ // 得到锁后,只有当实例为空时,才会去创建,否则解锁并返回
Inst = new singleton();
printf("this is called\n");
}
unlock();
}
return Inst;
}
};
singleton* singleton::Inst = NULL;
int main(){
singleton *ins = singleton::getIns();
system("pause");
}
1081

被折叠的 条评论
为什么被折叠?



