博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
学习设计模式(8)——单例模式2
阅读量:4067 次
发布时间:2019-05-25

本文共 1533 字,大约阅读时间需要 5 分钟。

  单例模式非常经典,很有用处,在某些特定用途特别有用。

  例如,日志模块,我们希望只存在一个实例,就可以用单例模式。

  下面是单例模式的经典代码,把下面 C++ 代码片段中的 Singleton 替换成实际类名, 快速得到一个单例类:

1.引用版本

#include 
using namespace std;class Singleton {public: static Singleton& Instance() { static Singleton theSingleton; return theSingleton; } /* more (non-static) functions here */ void dosome() { cout << "this is true" << endl; }private: Singleton(){} // ctor hidden Singleton(Singleton const&); // copy ctor hidden Singleton& operator=(Singleton const&); // assign op. hidden ~Singleton(){} // dtor hidden};int main (){ Singleton &s=Singleton::Instance(); s.dosome(); return 0;}//----

2.指针版本

#include 
using namespace std;class Singleton {public: static Singleton* Instance() { static Singleton theSingleton; return &theSingleton; } /* more (non-static) functions here */ void dosome() { cout << "this is true" << endl; }private: Singleton(){} // ctor hidden Singleton(Singleton const&); // copy ctor hidden Singleton& operator=(Singleton const&); // assign op. hidden ~Singleton(){} // dtor hidden};int main (){ Singleton *sc; sc = Singleton::Instance(); sc->dosome(); Singleton *sc2; sc2 = Singleton::Instance(); sc2->dosome(); if (sc == sc2) { cout << "The same" << endl; } return 0;}//--

  这是经典例子,记好,好用。

------------------

你可能感兴趣的文章
Visual Studio 2010:C++0x新特性
查看>>
所谓的进步和提升,就是完成认知升级
查看>>
如何用好碎片化时间,让思维更有效率?
查看>>
No.182 - LeetCode1325 - C指针的魅力
查看>>
Encoding Schemes
查看>>
带WiringPi库的交叉笔译如何处理二之软链接概念
查看>>
Java8 HashMap集合解析
查看>>
自定义 select 下拉框 多选插件
查看>>
gdb 调试core dump
查看>>
gdb debug tips
查看>>
linux和windows内存布局验证
查看>>
本地服务方式搭建etcd集群
查看>>
安装k8s Master高可用集群
查看>>
忽略图片透明区域的事件(Flex)
查看>>
移动端自动化测试-Windows-Android-Appium环境搭建
查看>>
Xpath使用方法
查看>>
移动端自动化测试-Mac-IOS-Appium环境搭建
查看>>
Selenium之前世今生
查看>>
Selenium-WebDriverApi接口详解
查看>>
Selenium-ActionChains Api接口详解
查看>>