#ifndef U_CORE_OBJECTFACTORY_H #define U_CORE_OBJECTFACTORY_H #include #include #include #include #include "Core/Object.h" namespace uLib { /** * @brief Singleton factory for dynamic Object instantiation based on class name. */ class ObjectFactory { public: typedef std::function 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 GetRegisteredClasses() const; private: ObjectFactory() = default; ~ObjectFactory() = default; // Prevent copy and assignment ObjectFactory(const ObjectFactory&) = delete; ObjectFactory& operator=(const ObjectFactory&) = delete; std::map m_factoryMap; }; /** * @brief Helper class to statically register a factory function. */ template 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 ULIB_REG_CONCAT(g_ObjectRegistrar_, __LINE__)(#className); #define ULIB_REGISTER_OBJECT_NAME(className, registeredName) \ static uLib::ObjectRegistrar ULIB_REG_CONCAT(g_ObjectRegistrar_, __LINE__)(registeredName); } // namespace uLib #endif // U_CORE_OBJECTFACTORY_H