ObjectFactory.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright (C) 2022 The V-Gears Team
  3. *
  4. * This file is part of V-Gears
  5. *
  6. * V-Gears is free software: you can redistribute it and/or modify it under
  7. * terms of the GNU General Public License as published by the Free Software
  8. * Foundation, version 3.0 (GPLv3) of the License.
  9. *
  10. * V-Gears is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. */
  15. #pragma once
  16. #include <map>
  17. #include <string>
  18. #include "common/scummsys.h"
  19. /**
  20. * Template function for creating an instance of Type.
  21. */
  22. template<typename BaseType, typename Type> BaseType *CreateObject(){return new Type();}
  23. /**
  24. * Generic factory for a class and its subclasses.
  25. */
  26. template<typename KeyType, typename BaseType> class ObjectFactory{
  27. public:
  28. /**
  29. * Register a new entry.
  30. *
  31. * @param key[in] The key to register the class under.
  32. */
  33. template<typename Type> void AddEntry(const KeyType &key) {
  34. registry_[key] = &CreateObject<BaseType, Type>;
  35. }
  36. /**
  37. * Creates an instance of some registered class.
  38. *
  39. * @param key[in] The key associated with the desired class.
  40. * @return NULL if the name is not registered, else an instance of the
  41. * associated class.
  42. */
  43. BaseType *Create(const KeyType &key) const{
  44. typename RegistryMap::const_iterator entry = registry_.find(key);
  45. if (entry == registry_.end()) return NULL;
  46. return (entry->second)();
  47. }
  48. private:
  49. /**
  50. * Function pointer to the object creation function.
  51. */
  52. typedef BaseType *(*CreateFunc)();
  53. /**
  54. * Type used to store registered entries.
  55. */
  56. typedef std::map<KeyType, CreateFunc> RegistryMap;
  57. /**
  58. * Map from an identifier to a creation function.
  59. */
  60. RegistryMap registry_;
  61. };