1 /* 2 * Copyright (c) 2022-2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef DEVICESTATUS_DELAYED_SP_SINGLETON_H 17 #define DEVICESTATUS_DELAYED_SP_SINGLETON_H 18 19 #include <mutex> 20 #include <memory> 21 #include <refbase.h> 22 23 #include "nocopyable.h" 24 25 namespace OHOS { 26 namespace Msdp { 27 namespace DeviceStatus { 28 #define DECLARE_DELAYED_SP_SINGLETON(MyClass) \ 29 public: \ 30 ~MyClass(); \ 31 private: \ 32 friend DelayedSpSingleton<MyClass>; \ 33 MyClass(); 34 35 template<typename T> 36 class DelayedSpSingleton : public NoCopyable { 37 public: 38 static void DestroyInstance(); 39 static sptr<T> GetInstance(); 40 41 private: 42 static std::mutex mutex_; 43 static sptr<T> instance_; 44 }; 45 46 template<typename T> 47 sptr<T> DelayedSpSingleton<T>::instance_ { nullptr }; 48 49 template<typename T> 50 std::mutex DelayedSpSingleton<T>::mutex_; 51 52 template<typename T> GetInstance()53sptr<T> DelayedSpSingleton<T>::GetInstance() 54 { 55 if (instance_ == nullptr) { 56 std::lock_guard<std::mutex> lock(mutex_); 57 if (instance_ == nullptr) { 58 instance_ = new T(); 59 } 60 } 61 return instance_; 62 } 63 64 template<typename T> DestroyInstance()65void DelayedSpSingleton<T>::DestroyInstance() 66 { 67 std::lock_guard<std::mutex> lock(mutex_); 68 if (instance_ != nullptr) { 69 instance_.clear(); 70 instance_ = nullptr; 71 } 72 } 73 } // namespace DeviceStatus 74 } // namespace Msdp 75 } // namespace OHOS 76 #endif // DEVICESTATUS_DELAYED_SP_SINGLETON_H 77