码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式的两种实现方式

时间:2015-08-06 16:46:19      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:c++

1.   饿汉模式:

#include <iostream>
using namespace std;
class Singleton {
public:
	static Singleton& getInst (void) {
		return s_inst;
	}
private:
	Singleton (void) {}
	Singleton (const Singleton&);
	static Singleton s_inst;
};
Singleton Singleton::s_inst;
int main (void) {
	Singleton& s1 = Singleton::getInst ();
	Singleton& s2 = Singleton::getInst ();
	Singleton& s3 = Singleton::getInst ();
	cout << &s1 << ' ' << &s2 << ' ' << &s3 << endl;
	return 0;
}

技术分享


2 . 懒汉模式

#include <iostream>
using namespace std;
class Singleton {
public:
	static Singleton& getInst (void) {
		if (! m_inst)
			m_inst = new Singleton;
		++m_cn;
		return *m_inst;
	}
	void releaseInst (void) {
		if (m_cn && --m_cn == 0)
			delete this;
	}
private:
	Singleton (void) {
		cout << "构造:" << this << endl;
	}
	Singleton (const Singleton&);
	~Singleton (void) {
		cout << "析构:" << this << endl;
		m_inst = NULL;
	}
	static Singleton* m_inst;
	static unsigned int m_cn;
};
Singleton* Singleton::m_inst = NULL;
unsigned int Singleton::m_cn = 0;
int main (void) {
	Singleton& s1 = Singleton::getInst ();
	Singleton& s2 = Singleton::getInst ();
	Singleton& s3 = Singleton::getInst ();
	cout << &s1 << ' ' << &s2 << ' ' << &s3 << endl;
	s3.releaseInst ();
	s2.releaseInst ();
	s1.releaseInst ();
	return 0;
}
技术分享

两种模式的区别:懒汉模式中只有一个静态变量,调一次通过getInst函数返回一次,大家都用的这一个变量。懒汉模式里边维护了一个静态指针变量和一个静态变量做计数器,每次调的时候会先判断有没有构造,如果构造过m_inst就是非空的,计数器直接++就好,调用析构的话就是判断计数器,没人用的时候释放这块内存。

版权声明:本文为博主原创文章,未经博主允许不得转载。

单例模式的两种实现方式

标签:c++

原文地址:http://blog.csdn.net/meetings/article/details/47318583

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!