• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  *     http://www.apache.org/licenses/LICENSE-2.0
7  * Unless required by applicable law or agreed to in writing, software
8  * distributed under the License is distributed on an "AS IS" BASIS,
9  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10  * See the License for the specific language governing permissions and
11  * limitations under the License.
12  */
13 
14 #ifndef OBJECT_FACTORY_H
15 #define OBJECT_FACTORY_H
16 #include <string>
17 #include <memory>
18 #include <unordered_map>
19 #include <functional>
20 #include <vector>
21 #include "no_copyable.h"
22 
23 namespace OHOS::Camera {
24 template<typename B, typename... Args>
25 class RegisterFactoty : public NoCopyable {
26 public:
27     using CreatorFunc = std::function<std::shared_ptr<B>(Args...)>;
Instance()28     static RegisterFactoty& Instance()
29     {
30         static RegisterFactoty r;
31         return r;
32     }
33 
34     template<typename T, typename std::enable_if_t<std::is_base_of_v<B, T>>* = nullptr>
DoRegister(const std::vector<std::string> & names,CreatorFunc f)35     std::string DoRegister(const std::vector<std::string>& names, CreatorFunc f)
36     {
37         std::string result;
38         for (const auto& it : names) {
39             result += it;
40             builder_.emplace(it, f);
41         }
42         return result;
43     }
44 
CreateShared(const std::string & name,Args...args)45     std::shared_ptr<B> CreateShared(const std::string& name, Args... args)
46     {
47         std::shared_ptr<B> result = nullptr;
48         for (auto&& [n, builder] : builder_) {
49             if (n == name) {
50                 result = builder(std::forward<Args>(args)...);
51                 break;
52             }
53         }
54         return result;
55     }
56     RegisterFactoty() = default;
57     ~RegisterFactoty() = default;
58 private:
59     std::unordered_map<std::string, CreatorFunc> builder_;
60 };
61 }
62 #endif