单例模式 详解

单例模式

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

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

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

执行结果

相关推荐
CSARImage1 小时前
C++读取exe程序标准输出
c++
一只小bit2 小时前
Qt 常用控件详解:按钮类 / 显示类 / 输入类属性、信号与实战示例
前端·c++·qt·gui
一条大祥脚2 小时前
26.1.9 轮廓线dp 状压最短路 构造
数据结构·c++·算法
项目題供诗2 小时前
C语言基础(一)
c++
@areok@3 小时前
C++opencv图片(mat)传入C#bitmap图片
开发语言·c++·opencv
鸽芷咕3 小时前
【2025年度总结】时光知味,三载同行:落笔皆是沉淀,前行自有光芒
linux·c++·人工智能·2025年度总结
羑悻的小杀马特3 小时前
指尖敲代码,笔尖写成长:2025年度总结与那些没说出口的碎碎念
linux·c++·博客之星·2025年度总结
linweidong3 小时前
C++thread pool(线程池)设计应关注哪些扩展性问题?
java·数据库·c++
cpp_25013 小时前
P2708 硬币翻转
数据结构·c++·算法·题解·洛谷
程序炼丹师5 小时前
va_list保姆级教程
c++