单例模式 详解

单例模式

简介: 让类只初始化一次, 然后不同的地方都能获取到同一个实例
这是非常常用的一种模式, 系统稍微大一点基本上都会用到. 在系统中, 不同模块的总管理类都已单例模式居多
这里我们不仅使用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;
}

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

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值