1 /* 2 * Copyright (c) 2021-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 POWERMGR_SP_SINGLETON_H 17 #define POWERMGR_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 DisplayPowerMgr { 27 template<typename T> 28 class DelayedSpSingleton : public NoCopyable { 29 public: 30 static sptr<T> GetInstance(); 31 static void DestroyInstance(); 32 33 private: 34 static sptr<T> instance_; 35 static std::mutex mutex_; 36 }; 37 38 template<typename T> 39 sptr<T> DelayedSpSingleton<T>::instance_ = nullptr; 40 41 template<typename T> 42 std::mutex DelayedSpSingleton<T>::mutex_; 43 44 template<typename T> GetInstance()45sptr<T> DelayedSpSingleton<T>::GetInstance() 46 { 47 if (!instance_) { 48 std::lock_guard<std::mutex> lock(mutex_); 49 if (instance_ == nullptr) { 50 instance_ = new T(); 51 } 52 } 53 54 return instance_; 55 } 56 57 template<typename T> DestroyInstance()58void DelayedSpSingleton<T>::DestroyInstance() 59 { 60 std::lock_guard<std::mutex> lock(mutex_); 61 if (instance_) { 62 instance_.clear(); 63 instance_ = nullptr; 64 } 65 } 66 } // namespace PowerMgr 67 } // namespace OHOS 68 #endif 69