69 lines
1.9 KiB
C++
69 lines
1.9 KiB
C++
#ifndef U_CORE_OBJECTFACTORY_H
|
|
#define U_CORE_OBJECTFACTORY_H
|
|
|
|
#include <string>
|
|
#include <map>
|
|
#include <vector>
|
|
#include <functional>
|
|
#include "Core/Object.h"
|
|
|
|
namespace uLib {
|
|
|
|
/**
|
|
* @brief Singleton factory for dynamic Object instantiation based on class name.
|
|
*/
|
|
class ObjectFactory {
|
|
public:
|
|
typedef std::function<Object*()> FactoryFunction;
|
|
|
|
/** @brief Get the singleton instance. */
|
|
static ObjectFactory& Instance();
|
|
|
|
/** @brief Register a factory function for a given class name. */
|
|
void Register(const std::string& className, FactoryFunction func);
|
|
|
|
/** @brief Create a new instance of the specified class. */
|
|
Object* Create(const std::string& className);
|
|
|
|
/** @brief Get the names of all registered classes. */
|
|
std::vector<std::string> GetRegisteredClasses() const;
|
|
|
|
private:
|
|
ObjectFactory() = default;
|
|
~ObjectFactory() = default;
|
|
|
|
// Prevent copy and assignment
|
|
ObjectFactory(const ObjectFactory&) = delete;
|
|
ObjectFactory& operator=(const ObjectFactory&) = delete;
|
|
|
|
std::map<std::string, FactoryFunction> m_factoryMap;
|
|
};
|
|
|
|
/**
|
|
* @brief Helper class to statically register a factory function.
|
|
*/
|
|
template <typename T>
|
|
class ObjectRegistrar {
|
|
public:
|
|
ObjectRegistrar(const std::string& className) {
|
|
ObjectFactory::Instance().Register(className, []() -> Object* { return new T(); });
|
|
}
|
|
};
|
|
|
|
#define ULIB_REG_CONCAT_IMPL(a, b) a##b
|
|
#define ULIB_REG_CONCAT(a, b) ULIB_REG_CONCAT_IMPL(a, b)
|
|
|
|
/**
|
|
* @brief Macro to register a class to the factory.
|
|
* Put this in the .cpp file of the class.
|
|
*/
|
|
#define ULIB_REGISTER_OBJECT(className) \
|
|
static uLib::ObjectRegistrar<className> ULIB_REG_CONCAT(g_ObjectRegistrar_, __LINE__)(#className);
|
|
|
|
#define ULIB_REGISTER_OBJECT_NAME(className, registeredName) \
|
|
static uLib::ObjectRegistrar<className> ULIB_REG_CONCAT(g_ObjectRegistrar_, __LINE__)(registeredName);
|
|
|
|
} // namespace uLib
|
|
|
|
#endif // U_CORE_OBJECTFACTORY_H
|