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 PASTEBOARD_SP_SINGLETON_H
17 #define PASTEBOARD_SP_SINGLETON_H
18 
19 #include <memory>
20 #include <mutex>
21 #include <refbase.h>
22 
23 #include "nocopyable.h"
24 
25 namespace OHOS {
26 namespace MiscServices {
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>
36 class DelayedSpSingleton : public NoCopyable {
37 public:
38     static sptr<T> GetInstance();
39     static void DestroyInstance();
40 
41 private:
42     static sptr<T> instance_;
43     static std::mutex mutex_;
44 };
45 
46 template<typename T>
47 sptr<T> DelayedSpSingleton<T>::instance_ = nullptr;
48 
49 template<typename T>
50 std::mutex DelayedSpSingleton<T>::mutex_;
51 
52 template<typename T>
GetInstance()53 sptr<T> DelayedSpSingleton<T>::GetInstance()
54 {
55     if (!instance_) {
56         std::lock_guard<std::mutex> lock(mutex_);
57         if (instance_ == nullptr) {
58             instance_ = new T();
59         }
60     }
61 
62     return instance_;
63 }
64 
65 template<typename T>
DestroyInstance()66 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 MiscServices
75 } // namespace OHOS
76 #endif
77