1# 单例模式 2## 概述 3### 简介 4根据不同的需求提供了三种不同的单例模式。class DelayedSingleton 是一个线程安全、内存安全的懒汉式单例(用到了智能指针和锁)。class DelayedRefSingleton 是一个函数线程安全的懒汉式单例(用到了普通指针和锁)。class Singleton 是一个饿汉式单例(没有用指针和锁)。 5 6## 涉及功能 7### class DelayedSingleton 8#### 接口说明 9|返回类型 | 名称 | 10| -------------- | -------------- | 11| void | **DestroyInstance**()<br>释放智能指针托管对象的管理权。 | 12| std::shared_ptr< T > | **GetInstance**()<br>创建唯一的实例对象并返回。 | 13 14### class DelayedRefSingleton 15#### 接口说明 16|返回类型 | 名称 | 17| -------------- | -------------- | 18| T& | **GetInstance**()<br>创建唯一的实例对象并返回。 | 19### class Singleton 20#### 接口说明 21|返回类型 | 名称 | 22| -------------- | -------------- | 23| T& | **GetInstance**()<br>返回唯一的实例对象。 | 24 25## 使用示例 26 271. 示例代码(伪代码) 28 29```c++ 30#include <iostream> 31#include "../include/singleton.h" 32 33using namespace OHOS; 34using namespace std; 35 36class DemoDelayedSingleton 37{ 38 DECLARE_DELAYED_SINGLETON(DemoDelayedSingleton); 39}; 40 41DemoDelayedSingleton :: DemoDelayedSingleton() {} 42DemoDelayedSingleton :: ~DemoDelayedSingleton() {} 43 44int main() 45{ 46 shared_ptr<DemoDelayedSingleton> ds1 = DelayedSingleton<DemoDelayedSingleton>::GetInstance(); 47 shared_ptr<DemoDelayedSingleton> ds2 = DelayedSingleton<DemoDelayedSingleton>::GetInstance(); 48 49 if (ds1 == ds2) { 50 cout << "Delayed singleton instances construct success!" << endl; 51 } 52 53 54 ds1.reset(); 55 ds2.reset(); 56 DelayedSingleton<DemoDelayedSingleton>::DestroyInstance(); 57 cout << "Delayed singleton instances destroy success!" << endl; 58 59} 60``` 61 622. 测试用例编译运行方法 63 64- 测试用例代码参见base/test/unittest/common/utils_singleton_test.cpp 65 66- 使用开发者自测试框架,使用方法参见:[开发自测试执行框架-测试用例执行](https://gitee.com/openharmony/testfwk_developer_test#%E6%B5%8B%E8%AF%95%E7%94%A8%E4%BE%8B%E6%89%A7%E8%A1%8C) 67 68- 使用以下具体命令以运行`singleton.h`对应测试用例 69 70```bash 71run -t UT -tp utils -ts UtilsSingletonTest 72``` 73 74## 常见问题 75调用`DestroyInstance()`方法后,`GetInstance()`方法将创建新的对象, 旧对象若存在外部的`std::shared_ptr`引用,则需要开发者自行释放以保证单例。