设计模式 学习笔记(1) 单例模式之懒汉式

本文介绍了一种懒汉式的单例模式实现方法,并通过C++代码示例展示了如何确保线程安全地创建单例对象。同时,文章还提供了一个利用C++11标准中的`std::call_once`和`std::once_flag`来简化多线程环境下单例对象初始化的方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

**懒汉式构造单例类**

懒汉式,指的就是需要时再构造(延迟构造),在效率上会优于饿汉式,因为饿汉式在进入 main 之前就要构造,懒汉式不用。

基本特点是:线程不安全

基本模板(加锁):

#include <bits/stdc++.h>
#define rep( i , j , n ) for ( int i = int(j) ; i < int(n) ; ++i )
#define dew( i , j , n ) for ( int i = int(n-1) ; i > int(j) ; --i )
#define _PATH __FILE__ , __LINE__
typedef std::pair < int , int > P ;
using std::cin ;
using std::cout ;
using std::endl ;
using std::string ;

class Entity final {
public:
    // 获取单例类实例的入口
	static Entity *getInstance() {
		if ( null == nullptr ) {
			myMutex.lock() ;
			if ( null == nullptr ) {
				null = new Entity ;
			}
			myMutex.unlock() ;
		}
		return null ;
	}
private:
	// 构造函数设为 private
	explicit Entity() = default ;
	~Entity() noexcept = default ;
	Entity(const Entity &) = delete ;
	Entity& operator=(const Entity &) = delete ;
	Entity& operator=(const Entity &&) = delete ;


	class Litter {
	public:
		~Litter() {
			cout << "\n清理单例类" << endl ;
			if ( null not_eq nullptr )
				delete null ;
			null = nullptr ;
		}
	} ;
private:
	static Entity *null ;
	// GC 清理类
	static Litter litter ;
	// 设置一把锁
	static std::mutex myMutex ;
} ;
Entity* Entity::null ;
Entity::Litter Entity::litter ;
std::mutex Entity::myMutex ;


int main () {
	constexpr int N = 10 ;
	Entity *Instance[N] ;
	rep ( i , 0 , N )
	    Instance[i] = Entity::getInstance() ;
	rep ( i , 0 , N )
	    cout << "Instance[ " << i << " ] = " << Instance[i] << endl ;
	rep ( i , 0 , N )
	    Instance[i] = nullptr ;
	return 0 ;
}

优点:双检锁,保证了线程安全;两次判断是否为 nullptr, 避免多次加锁解锁。

缺点:频繁的加解锁操作,损失了性能。

 

两种单例模式的分析比较参考:单例模式的分析

 

 

2018.8.3

C++11 的 std::call_once 和 std::once_flag 搭配使用,可以保证在多个线程中,只构造一次,具体实现如下:

static Entity *getInstance() {
	try {
		static std::once_flag flag ;
		std::call_once(flag, [&](){
			cout << "构造单例类\n\n" ;
			null = new Entity ;
		}) ;
		if ( null == nullptr )
			throw std::bad_alloc() ;
	} catch ( std::exception &e ) {
		cout << e.what() << endl ;
	}
	return null ;
}

程序运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值