1 /* 2 * Copyright (c) 2021 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 SP_SINGLETON_H 17 #define SP_SINGLETON_H 18 19 #include <memory> 20 #include <mutex> 21 #include <refbase.h> 22 #include "nocopyable.h" 23 24 namespace OHOS { 25 namespace PowerMgr { 26 #define DECLARE_DELAYED_SP_SINGLETON(MyClass) \ 27 public: \ 28 ~MyClass(); \ 29 private: \ 30 friend DelayedSpSingleton<MyClass>; \ 31 MyClass(); 32 33 template<typename T> 34 class DelayedSpSingleton : public NoCopyable { 35 public: 36 static sptr<T> GetInstance(); 37 static void DestroyInstance(); 38 39 private: 40 static sptr<T> instance_; 41 static std::mutex mutex_; 42 }; 43 44 template<typename T> 45 sptr<T> DelayedSpSingleton<T>::instance_ = nullptr; 46 47 template<typename T> 48 std::mutex DelayedSpSingleton<T>::mutex_; 49 50 template<typename T> GetInstance()51sptr<T> DelayedSpSingleton<T>::GetInstance() 52 { 53 if (!instance_) { 54 std::lock_guard<std::mutex> lock(mutex_); 55 if (instance_ == nullptr) { 56 instance_ = new T(); 57 } 58 } 59 60 return instance_; 61 } 62 63 template<typename T> DestroyInstance()64void DelayedSpSingleton<T>::DestroyInstance() 65 { 66 std::lock_guard<std::mutex> lock(mutex_); 67 if (instance_) { 68 instance_.clear(); 69 instance_ = nullptr; 70 } 71 } 72 } // namespace ThermalMgr 73 } // namespace OHOS 74 #endif // SP_SINGLETON_H 75