单例模式 详解

单例模式

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

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

这里我们不仅使用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;
}

执行结果

相关推荐
JCBP_29 分钟前
QT(4)
开发语言·汇编·c++·qt·算法
会开花的二叉树1 小时前
继承与组合:C++面向对象的核心
java·开发语言·c++
潮汐退涨月冷风霜2 小时前
数字图像处理(1)OpenCV C++ & Opencv Python显示图像和视频
c++·python·opencv
第七序章3 小时前
【C++STL】list的详细用法和底层实现
c语言·c++·自然语言处理·list
逆小舟5 小时前
【Linux】人事档案——用户及组管理
linux·c++
风中的微尘9 小时前
39.网络流入门
开发语言·网络·c++·算法
混分巨兽龙某某10 小时前
基于Qt Creator的Serial Port串口调试助手项目(代码开源)
c++·qt creator·串口助手·serial port
小冯记录编程10 小时前
C++指针陷阱:高效背后的致命危险
开发语言·c++·visual studio
C_Liu_11 小时前
C++:类和对象(下)
开发语言·c++
coderxiaohan11 小时前
【C++】类和对象1
java·开发语言·c++