单例模式 详解

单例模式

简介: 让类只初始化一次, 然后不同的地方都能获取到同一个实例

这是非常常用的一种模式, 系统稍微大一点基本上都会用到. 在系统中, 不同模块的总管理类都已单例模式居多

这里我们不仅使用c++实现单例模式, 也会用python2实现一遍

python代码

想要看更详细的python单例模式的不同写法, 参照: python单例模式的几种写法

python 复制代码
class Singleton(type):

	def __call__(cls, *args, **kwargs):
		if not hasattr(cls, '_instance'):
			cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
		return cls._instance

class Test1(object):

	__metaclass__ = Singleton

	def __init__(self):
		pass


if __name__ == '__main__':
	t1 = Test1()
	t2 = Test1()

	if t1 is t2:
		print 'Singleton'

执行结果

c++代码
cpp 复制代码
class System
{
private:
	static System* _instance;
public:
	static System* get_instance()
	{
		if (not _instance)
			_instance = new System();
		return _instance;
	}
};

System* System::_instance = nullptr;


int main()
{
	System* s1 = System::get_instance();
	System* s2 = System::get_instance();
	if (s1 == s2)
		cout << "singleton!" << endl;
	return 0;
}

执行结果

相关推荐
xlp666hub18 小时前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
会员源码网20 小时前
构造函数抛出异常:C++对象部分初始化的陷阱与应对策略
c++
xlp666hub1 天前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
不想写代码的星星1 天前
static 关键字:从 C 到 C++,一篇文章彻底搞懂它的“七十二变”
c++
xlp666hub2 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
不想写代码的星星2 天前
C++继承、组合、聚合:选错了是屎山,选对了是神器
c++
不想写代码的星星3 天前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
樱木Plus5 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit7 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_8 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++