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