您的位置:首页 > 娱乐 > 八卦 > 单例模式 详解

单例模式 详解

2024/10/7 4:30:02 来源:https://blog.csdn.net/qq_40666620/article/details/141393493  浏览:    关键词:单例模式 详解

单例模式

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

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com