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