模式五:单例模式(Singleton Pattern)——创建独一无二的对象

单例模式

确保一个类只有一个实例,并提供一个全局访问点。

应用分析

还有一些对象其实我们只需要一个,比如说:线程池(threadpool)、缓存(cache)、对话框、处理偏好设置和注册表的对象、日志对象,充当打印机、显卡等设备的驱动程序对象。事实上,这类对象只能有一个实例,如果制造出多个实例,就会导致许多问题产生,例如:程序的行为异常、资源使用过量、或者是不一致的结果。

代码分析

//Singleton.h
//经典的单例模式
#ifndef SINGLETON_H
#define SINGLETON_H

#include <iostream>

class Singleton
{
private:
	static Singleton *uniqueInstance;//声明一个静态变量来记录Singleton类的唯一实例

	Singleton(){}//把构造函数声明为私有的,只能自Singleton类内才可以调用它
public:
	static Singleton * getInstance()//实例化对象,并返回实例,只有在需要时,才实例化
	{
		if(uniqueInstance==NULL)
			uniqueInstance=new Singleton();
		return uniqueInstance;
	}
	//这里是其他的有用方法
	void fun()
	{
		std::cout<<"Singleton Pattern"<<std::endl;
	}
};
Singleton *Singleton::uniqueInstance=NULL;//定义uniqueInstance,分配空间

#endif


//Main.cpp
//测试程序
#include "Singleton.h"

int main()
{
	Singleton *s=Singleton::getInstance();
	s->fun();
	return 0;
}


模式分析——模式问题:多线程处理中,仍有可能造成实例化多个对象的情况,如第一次调用getInstance时,在if判断之后中断。

解决方案:

1.使用同步锁,如果getInstance的性能对应用程序不是很关键的话——设置uniqueSingleton为同步变量

2.使用“急切”创建实例,而不用延迟实例化的做法

Singleton *Singleton::uniqueInstance=new Singleton();//定义uniqueInstance时,直接创建实例

3.用“双重检查加锁”,在getInstance中减少同步使用

static Singleton * getInstance()//实例化对象,并返回实例,只有在需要时,才实例化
{
	if(uniqueInstance==NULL)
	{
		//在此加锁
		if(uniqueInstance==NULL)
			uniqueInstance=new Singleton();
	}
	return uniqueInstance;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值