Anonymous
9/10/2025, 5:48:40 AM
No.106542433
Am I using a factory pattern correctly here? I want other components of my system to be able to construct derived classes without knowing what those derived classes are. I also want to be able to restrict on a case by case basis what derived classes a particular factory is allowed to create. I'm doing this by having derived classes 'register' themselves with the factory, providing both a unique ID and a function to create them. I plan to place the create method as a static method inside of each Derived just to keep all of the code related to a specific derived in one place (rather than like a giant switch case inside the BaseFactory)
static std::unique_ptr<Base> create() {
return std::make_unique<Derived>();
}
class BaseFactory {
public:
std::unique_ptr<Base> create(std::type_index base) {
return mapping[base]();
}
void registerBase(std::type_index base, std::function<std::unique_ptr<Base>()> create) {
mapping[base] = create;
}
std::map<std::type_index, std::function<std::unique_ptr<Base>()>> mapping;
};
factory.registerBase(std::type_index(typeid(Derived)), Derived::create);
static std::unique_ptr<Base> create() {
return std::make_unique<Derived>();
}
class BaseFactory {
public:
std::unique_ptr<Base> create(std::type_index base) {
return mapping[base]();
}
void registerBase(std::type_index base, std::function<std::unique_ptr<Base>()> create) {
mapping[base] = create;
}
std::map<std::type_index, std::function<std::unique_ptr<Base>()>> mapping;
};
factory.registerBase(std::type_index(typeid(Derived)), Derived::create);