设计模式笔记1--单例模式
1、单例模式介绍
Head First设计模式中解释:用来创建独一无二的,只能有一个实例的对象的入场券。即:该类只能有一个示例,其实现逻辑一般是 构造函数声明为private或protect防止被外部函数实例化,内部保存一个private static的类指针保存唯一的实例,实例的动作由一个public的类方法完成,该方法返回单例类唯一的实例。
单例实现方法被分为两大类:懒汉与饿汉。
懒汉:故名思义,不到万不得已就不会去实例化类,也就是说在第一次用到类实例的时候才会去实例化;
饿汉:饿了肯定要饥不择食。所以在单例类定义的时候就进行实例化。
特点与选择:
由于要进行线程同步,所以在访问量比较大,或者可能访问的线程比较多时,采用饿汉实现,可以实现更好的性能,这是以空间换时间。在访问量较小时,采用懒汉实现。这是以时间换空间。
2、代码
1)饿汉模式
#include <iostream>
#include <pthread.h>
using namespace std;
class Singleton
{
protected:
Singleton(){}
private:
static Singleton *instance;
public:
static Singleton *GetInstance()
{
return instance;
}
};
Singleton* Singleton::instance = new Singleton();
int main()
{
Singleton *p1 = Singleton::GetInstance();
Singleton *p2 = Singleton::GetInstance();
if (p1 == p2)
{
cout<<"Two objects is the same instance"<<endl;
}
return 0;
}
2)懒汉模式
#include <iostream>
#include <pthread.h>
using namespace std;
class Singleton
{
protected:
Singleton(){}
private:
static Singleton *instance;
static pthread_mutex_t mutex;
public:
static Singleton *GetInstance()
{
if(NULL == instance){
pthread_mutex_lock(&mutex);
if (NULL == instance)
{
instance = new Singleton();
}
pthread_mutex_unlock(&mutex);
}
return instance;
}
};
Singleton* Singleton::instance = NULL;
pthread_mutex_t Singleton::mutex = NULL;
int main()
{
Singleton *p1 = Singleton::GetInstance();
Singleton *p2 = Singleton::GetInstance();
if (p1 == p2)
{
cout<<"Two objects is the same instance"<<endl;
}
return 1;
}
3、说明
当前已在mingw32(gcc 4.9.2)上测试通过。