Files
Destrum/destrum/include/destrum/Serialization/ComponentFactory.h
T

38 lines
941 B
C++

#ifndef DESTRUM_COMPONENTFACTORY_H
#define DESTRUM_COMPONENTFACTORY_H
#include <functional>
#include <memory>
#include <string>
#include <unordered_map>
#include <destrum/ObjectModel/Component.h>
#include <destrum/ObjectModel/GameObject.h>
class ComponentFactory final {
public:
using CreateFn = std::function<Component*(GameObject&)>;
static void Register(const std::string& typeName, CreateFn createFn) {
Registry()[typeName] = std::move(createFn);
}
static Component* Create(const std::string& typeName, GameObject& owner) {
const auto it = Registry().find(typeName);
if (it == Registry().end()) {
return nullptr;
}
return it->second(owner);
}
private:
static std::unordered_map<std::string, CreateFn>& Registry() {
static std::unordered_map<std::string, CreateFn> registry;
return registry;
}
};
#endif //DESTRUM_COMPONENTFACTORY_H