factory.h 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #pragma once
  2. #include "spawn_type.h"
  3. #include "unit.h"
  4. #include <functional>
  5. #include <memory>
  6. #include <string>
  7. #include <unordered_map>
  8. namespace Game::Units {
  9. class UnitFactoryRegistry {
  10. public:
  11. using Factory = std::function<std::unique_ptr<Unit>(Engine::Core::World &,
  12. const SpawnParams &)>;
  13. void registerFactory(SpawnType type, Factory f) {
  14. m_factories[type] = std::move(f);
  15. }
  16. auto create(SpawnType type, Engine::Core::World &world,
  17. const SpawnParams &params) const -> std::unique_ptr<Unit> {
  18. auto it = m_factories.find(type);
  19. if (it == m_factories.end()) {
  20. return nullptr;
  21. }
  22. return it->second(world, params);
  23. }
  24. auto create(TroopType type, Engine::Core::World &world,
  25. const SpawnParams &params) const -> std::unique_ptr<Unit> {
  26. const SpawnType spawn_type = spawn_typeFromTroopType(type);
  27. return create(spawn_type, world, params);
  28. }
  29. private:
  30. std::unordered_map<SpawnType, Factory> m_factories;
  31. };
  32. void registerBuiltInUnits(UnitFactoryRegistry &reg);
  33. } // namespace Game::Units