一、原来的单例模式设计流程
1、构造函数修改为私有;
2、定义一个私有的静态成员变量(返回指针);
3、定义一个全局的静态成员函数(返回指针);
4、通过全局静态成员函数实现控制类的实例化的唯一性。
二话不说上代码,以前代码:
#include <pthread.h>//pthread.h是在linux编程环境下才使用
using namespace std;
class Singleton
{
private:
static Singleton* m_instance;
static pthread_mutex_t mutex;
Singleton() {}
~Singleton() {}
public:
static Singleton* getInstance();//单例模式中只有getInstance()方法才是public的,互斥锁mutex,构造函数,单例变量都应该是private的
};
Singleton* Singleton::m_instance= NULL;//注意static变量,static函数只能调用static变量,所以mutex,m_instance都应该是static成员,并且static非const成员不可在类内定义,需要在全局变量中声明
pthread_mutex_t Singleton::mutex;
Singleton* Singleton::getInstance()
{
if(m_instance==NULL)
{
pthread_mutex_lock(&mutex);//为保证线程安全,需要双重锁的机制实现
if(m_instance==NULL)
{
m_instance = new Singleton();
}
pthread_mutex_unlock(&mutex);
}
return m_instance;
};
int main()
{
Singleton *s1=Singleton::getInstance();
Singleton *s2=Singleton::getInstance();
if(s1==s2)
{
cout<<"s1==s2"<<endl;
}else
{
cout<<"s1!=s1"<<endl;
}
return 0;
}
二、C++11下的单例模式
动机:在软件系统中,经常有这样特殊的类,必须保证他们在系统中只存在一个实例,才能确保它们的逻辑正确性、以及良好的效率。 绕过常规的构造器,提供一种机制来保证一个类只有一个实例。
定义:保证一个类仅有一个实例,并提供一个实例的全局访问点。
1、C++11中可以保证static变量时多线程安全的,在底层实现了加锁操作,所以不需要像以前那样自己写加锁操作。
2、由于是一个static对象,可以保证对象只生成一次;
3、在程序结束的时候,系统会调用对应的析构函数;如果是new出来的对象,程序结束的时候,系统不会自动调用析构函数。
4、getInstance()的返回值需要是指针或者引用,不然会出现值拷贝;最好是指针,用户使用起来会方便一些;如果返回指针每次使用该类的时候都需要GetInstance();返回指针就可以使用指针调用该类中的函数了。
一言不合就上代码:
#include <iostream>
#include <stdio.h>
/*
1、单例模式c++11下保证唯一性
*/
using namespace std;
class Singleton
{
private:
Singleton(){};
~Singleton(){};
public:
static Singleton *get_instance();
};
Singleton* Singleton::get_instance()
{
static Singleton instance;
return &instance;
}
int main()
{
Singleton *s1=Singleton::get_instance();
Singleton *s2=Singleton::get_instance();
Singleton *s3=Singleton::get_instance();
Singleton *s4=Singleton::get_instance();
if(s1 == s2 && s1 == s3 && s2 == s3 &&
s1 == s4 && s2 == s4 && s3 == s4){
cout<<"s1==s2==s3==s4"<<endl;
}else{
cout<<"s1!=s1"<<endl;
}
return 0;
}