Apache Singa
A General Distributed Deep Learning Library
factory.h
1 /************************************************************
2 *
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 *
20 *************************************************************/
21 
22 #ifndef SINGA_UTILS_FACTORY_H_
23 #define SINGA_UTILS_FACTORY_H_
24 
25 #include <functional>
26 #include <map>
27 #include <string>
28 
29 #include "singa/utils/logging.h"
34 #define CreateInstance(SubClass, BaseClass) \
35  [](void)->BaseClass* {return new SubClass();}
36 
44 template<typename T, typename ID = std::string>
45 class Factory {
46  public:
54  static void Register(const ID& id,
55  const std::function<T*(void)>& creator) {
56  Registry* reg = GetRegistry();
57  // CHECK(reg->find(id) == reg->end())
58  // << "The id " << id << " has been registered";
59  (*reg)[id] = creator;
60  }
61 
67  static T* Create(const ID& id) {
68  Registry* reg = GetRegistry();
69  CHECK(reg->find(id) != reg->end())
70  << "The creation function for " << id << " has not been registered";
71  return (*reg)[id]();
72  }
73 
74  static const std::vector<ID> GetIDs() {
75  std::vector<ID> keys;
76  for (const auto entry : *GetRegistry())
77  keys.push_back(entry.first);
78  return keys;
79  }
80 
81  private:
82  // Map that stores the registered creation functions
83  typedef std::map<ID, std::function<T*(void)>> Registry;
84  static Registry* GetRegistry() {
85  static Registry reg;
86  return &reg;
87  }
88 };
89 
90 template<typename Base, typename Sub, typename ID = std::string>
91 class Registra {
92  public:
93  Registra(const ID& id) {
94  Factory<Base, ID>::Register(id, [](void) { return new Sub(); });
95  }
96 };
97 #endif // SINGA_UTILS_FACTORY_H_
Definition: factory.h:91
Factory template to generate class (or a sub-class) object based on id.
Definition: factory.h:45
static void Register(const ID &id, const std::function< T *(void)> &creator)
Register functions to create user defined classes.
Definition: factory.h:54
static T * Create(const ID &id)
create an instance by providing its id
Definition: factory.h:67