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