0
点赞
收藏
分享

微信扫一扫

删除Linux最近几条命令

我是小瘦子哟 2024-08-22 阅读 24

单例模式

简介: 让类只初始化一次, 然后不同的地方都能获取到同一个实例
这是非常常用的一种模式, 系统稍微大一点基本上都会用到. 在系统中, 不同模块的总管理类都已单例模式居多
这里我们不仅使用c++实现单例模式, 也会用python2实现一遍

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++代码
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;
}

执行结果
在这里插入图片描述

举报

相关推荐

0 条评论