单例模式,是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中一个类只有一个实例。即一个类只有一个对象实例。显然单例模式的要点有三个;一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。从具体实现角度来说,就是以下三点:一是单例模式的类只提供私有的构造函数,二是类定义中含有一个该类的静态私有对象,三是该类提供了一个静态的公有的函数用于创建或获取它本身的静态私有对象。
(1)单线程时单例模式:(代码如下)
class Single
{
private:
static Single* instance;
Single(){};
public:
static Single getInstance()
{
if(instance == NULL)
{
instance = new Single();
}
return instance;
}
};
(2)在使用单例类的时候,一定要小心多个线程的影响,在单线程环境中,单例类会正常工作,而在多线程环境中,如果没有对获取实例的函数进行同步,就有可能创建多个实例。如果线程1刚进入if,还没有执行new语句,这个时候线程2也进入了if,这种情况下就会出现多个实例。下面是多线程中单例模式的使用方法:(代码如下)
#include <iostream>
#include <pthread.h>
using namespace std;
static pthread_mutex_t* mutex;
class Single;
class Single
{
private:
Single(){};
public:
static Single* instance;
static Single* getInstance()
{
if(instance == NULL)
{
pthread_mutex_lock(mutex);
if(instance == NULL)
{
instance = new Single();
}
pthread_mutex_unlock(mutex);
}
else
{
cout<<"资源已被占用"<<endl;
}
return instance;
}
void display()
{
cout<<"单例模式"<<endl;
}
};
Single* Single::instance = NULL;
int main()
{
pthread_mutex_init(mutex, NULL);
Single* sing = Single::getInstance();
sing->display();
Single* s = Single::getInstance();
s->display();
return 0;
}