单件(Singleton)模式
一、问题的提出
二、经典单件模式的实现
#ifndef SINGLETON__H
#define SINGLETON__H
#include <iostream>
using namespace std;
class Singleton
{
private:
static Singleton* uniqueInstance; //唯一的实例对象
Singleton(); //将构造函数定义为私有,这样外部就不能调用构造函数创建对象
public:
static Singleton* getInstance(); //提供给外部获取唯一实例对象的方法
};
#endifcpp文件:
#include "Singleton.h"
Singleton::Singleton()
{}
Singleton* Singleton::getInstance()
{
if(NULL == uniqueInstance)
{
uniqueInstance = new Singleton();//此处创建唯一对象,构造函数为私有,只有本类中能调用
}
return uniqueInstance;
}单件模式定义:确保一个类只有一个实例,并提供一个全局访问点。
三、使用注意
Singleton* Singleton::getInstance()
{
LOCK();//线程加锁
if(NULL == uniqueInstance)
{
uniqueInstance = new Singleton();//此处创建唯一对象,构造函数为私有,只有本类中能调用
}
UNLOCK();
return uniqueInstance;
}<span style="white-space:pre"> </span>Singleton* Singleton::uniqueInstance = new Singleton(); 然后getInstance()函数可以这样写<span style="white-space:pre"> </span>Singleton* Singleton::getInstance()
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>return uniqueInstance;
<span style="white-space:pre"> </span>} 这样就可以不用加锁控制,减少性能损失。
6482


模式&spm=1001.2101.3001.11974&articleId=35560209&d=1&t=3&u=51728e81be00495b831a4a8cf9cbb5e6)

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



