Overte C++ Documentation
Factory.h
1 //
2 // Created by Bradley Austin Davis 2015/10/09
3 // Copyright 2015 High Fidelity, Inc.
4 //
5 // Distributed under the Apache License, Version 2.0.
6 // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
7 //
8 
9 #pragma once
10 #ifndef hifi_Shared_Factory_h
11 #define hifi_Shared_Factory_h
12 
13 #include <functional>
14 #include <map>
15 #include <memory>
16 
17 namespace hifi {
18 
19  template <typename T, typename Key>
20  class SimpleFactory {
21  public:
22  using Pointer = std::shared_ptr<T>;
23  using Builder = std::function<Pointer()>;
24  using BuilderMap = std::map<Key, Builder>;
25 
26  void registerBuilder(const Key name, Builder builder) {
27  // FIXME don't allow name collisions
28  _builders[name] = builder;
29  }
30 
31  Pointer create(const Key name) const {
32  const auto& entryIt = _builders.find(name);
33  if (entryIt != _builders.end()) {
34  return (*entryIt).second();
35  }
36  return Pointer();
37  }
38 
39  template <typename Impl>
40  class Registrar {
41  public:
42  Registrar(const Key name, SimpleFactory& factory) {
43  factory.registerBuilder(name, [] { return std::make_shared<Impl>(); });
44  }
45  };
46  protected:
47  BuilderMap _builders;
48  };
49 }
50 
51 #endif