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