1 /*
2  * Copyright (c) 2023 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 FOUNDATION_BUNDLEMANAGER_BUNDLE_FRAMEWORK_INNERKITS_APPEXECFWK_CORE_EXT_INCLUDE_BUNDLE_MGR_EX_REGISTER_H
17 #define FOUNDATION_BUNDLEMANAGER_BUNDLE_FRAMEWORK_INNERKITS_APPEXECFWK_CORE_EXT_INCLUDE_BUNDLE_MGR_EX_REGISTER_H
18 
19 #include <functional>
20 #include <mutex>
21 #include <string>
22 #include <unordered_map>
23 
24 #include "bundle_mgr_ext.h"
25 #include "nocopyable.h"
26 
27 namespace OHOS {
28 namespace AppExecFwk {
29 using CreateFunc = std::function<std::shared_ptr<BundleMgrExt>(void)>;
30 class BundleMgrExtRegister {
31 public:
32     static BundleMgrExtRegister &GetInstance();
33 
34     ~BundleMgrExtRegister() = default;
35 
36     void RegisterBundleMgrExt(const std::string& bundleExtName, const CreateFunc& createFunc);
37     std::shared_ptr<BundleMgrExt> GetBundleMgrExt(const std::string &bundleExtName);
38 private:
39     static std::mutex mutex_;
40     mutable std::mutex BundleMgrExtMutex_;
41     BundleMgrExtRegister() = default;
42     std::unordered_map<std::string, CreateFunc> bundleMgrExts_;
43 
44     DISALLOW_COPY_AND_MOVE(BundleMgrExtRegister);
45 };
46 
47 #define REGISTER_BUNDLEMGR_EXT(className)                                                                \
48     __attribute__((constructor)) void RegisterBundleMgrExt##className() {                               \
49         BundleMgrExtRegister::GetInstance().RegisterBundleMgrExt(#className, []()->std::shared_ptr<BundleMgrExt> { \
50             return std::make_shared<className>();                                                             \
51         });                                                                                   \
52     }
53 } // AppExecFwk
54 } // OHOS
55 #endif // FOUNDATION_BUNDLEMANAGER_BUNDLE_FRAMEWORK_INNERKITS_APPEXECFWK_CORE_EXT_INCLUDE_BUNDLE_MGR_EX_REGISTER_H
56