1/*
2 * Copyright (c) 2024 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 AUTO_REGISTER_H
17#define AUTO_REGISTER_H
18
19#include <functional>
20#include <iostream>
21#include <memory>
22#include <unordered_map>
23
24namespace OHOS::UpdateEngine {
25template <class INTERFACE> class Container {
26public:
27    using FuncType = std::function<std::shared_ptr<INTERFACE>()>;
28
29    ~Container() = default;
30    // 单例模式
31    static Container &Instance()
32    {
33        static Container instance; // c++11 静态局部变量保证线程安全
34        return instance;
35    }
36
37    bool RegisterType(uint32_t functionType, FuncType type)
38    {
39        if (createMap_.find(functionType) != createMap_.end()) {
40            return false;
41        }
42        return createMap_.emplace(functionType, type).second;
43    }
44
45    std::shared_ptr<INTERFACE> GetPtr(uint32_t functionType)
46    {
47        if (createMap_.find(functionType) == createMap_.end()) {
48            return nullptr;
49        }
50        FuncType function = createMap_[functionType];
51        // 获取容器中对象时实例化
52        return function();
53    }
54
55private:
56    Container() = default;
57    Container(const Container &) = delete;
58    Container(Container &&) = delete;
59
60private:
61    // 存储注入对象的回调函数
62    std::unordered_map<uint32_t, FuncType> createMap_;
63};
64
65template <typename INTERFACE, typename T> class NapiAutoRegister {
66public:
67    explicit NapiAutoRegister(uint32_t FuncType)
68    {
69        Container<INTERFACE>::Instance().RegisterType(FuncType, []() { return std::make_shared<T>(); });
70    }
71};
72} // namespace OHOS::UpdateEngine
73#endif // AUTO_REGISTER_H