您可以从每个对象工厂创建一个映射typeOfObject_enum
,然后您可以根据需要在映射中注册工厂。
每个对象工厂都可能类似于std::function<std::unique_ptr<Entity>()>
:
enum class StationaryObjectType{WALL, FIRE_TURRET, WATER_TURRET};
const size_t STATIONARY_OBJECT_TYPE_COUNT = 3;
using EntityFactory = std::function<std::unique_ptr<Entity>()>;
class StationaryObjectFactory {
std::array<EntityFactory, STATIONARY_OBJECT_TYPE_COUNT> factory_map;
public:
void registerFactory(StationaryObjectType type, EntityFactory factory){
factory_map[static_cast<size_t>(type)] = std::move(factory);
}
std::unique_ptr<Entity> create(StationaryObjectType type){
auto factory = factory_map[static_cast<size_t>(type)];
if (!factory)
return nullptr;
return factory();
}
};
int main() {
StationaryObjectFactory factory;
// Register lambdas as the factory objects
factory.registerFactory(StationaryObjectType::WALL, []{
return std::make_unique<Wall>();
});
factory.registerFactory(StationaryObjectType::FIRE_TURRET, []{
return std::make_unique<FireTurret>();
});
auto wall = factory.create(StationaryObjectType::WALL);
auto fire_turret = factory.create(StationaryObjectType::FIRE_TURRET);
auto water_turret = factory.create(StationaryObjectType::WATER_TURRET);
assert(wall != nullptr);
assert(fire_turret != nullptr);
assert(water_turret == nullptr); // No WATER_TURRET factory registered
}
现场演示。
或者,如果您愿意,可以使用抽象工厂类的实现:
class EntityFactory {
public:
virtual ~EntityFactory(){}
virtual std::unique_ptr<Entity> operator()() = 0;
};
class WallFactory : public EntityFactory {
public:
std::unique_ptr<Entity> operator()() override {
return std::make_unique<Wall>();
}
};
class FireTurretFactory : public EntityFactory {
public:
std::unique_ptr<Entity> operator()() override {
return std::make_unique<FireTurret>();
}
};
现场演示。