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