2021-6-24 设计模式-单例模式

单例模式:

单例模式的核心结构只包含一个被称为单例的特殊类,目的是保证一个类仅有一个实例,并提供一个访问它的全局访问点,该实例被所有程序模块共享

特点:

  • 构造函数私有化
  • 实例只有一个,提供一个全局访问点
	/*
	* 懒汉式
	* 缺陷:1. 懒汉式在单线程下是安全的,但是多线程下,多个线程可能同时调用GetInstance创建实例给Instance,出现错误
	*/
class singleton{
privete:
	singleton(){};					//私有构造函数
	static singleton* Instance;		//类静态成员
public:
	static singleton* GetInstance{		//全局访问点
		if(Instance==NULL){				//判断是否被初始化了
			Instance=new SINGLETEON();
		}
		return Instance;
	}
}


	/*
	* 改进的懒汉式
	* 方法:加锁,解决线程安全的问题
	* 缺陷:效率低
	*/
class singleton{
privete:
	singleton(){};					
	static singleton* Instance;		
public:
	static singleton* GetInstance{		
		if(Instance==NULL){				
			lock();		//上锁,防止防止其他线程继续生成实例
			if(Instance==NULL){		//判断一下是否其他线程已经生成了实例
				Instance=new SINGLETEON();
				}
			unlock();		//解锁
		}
		return Instance;
		}
}

	/*
	* 饿汉式
	* 方法:事先实例化,通过空间换时间,线程安全
	*/
class singleton{
privete:
	singleton(){};					
public:
	static singleton* GetInstance{
		static singleton Instance;
		return &Instance;
	}
}
posted @ 2021-06-24 14:27  shenlei_blog  阅读(47)  评论(0)    收藏  举报