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