objectFactory.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* ScummVM Tools
  2. *
  3. * ScummVM Tools is the legal property of its developers, whose
  4. * names are too numerous to list here. Please refer to the
  5. * COPYRIGHT file distributed with this source distribution.
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU General Public License
  9. * as published by the Free Software Foundation; either version 2
  10. * of the License, or (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  20. */
  21. #ifndef DEC_OBJECTFACTORY_H
  22. #define DEC_OBJECTFACTORY_H
  23. #include <map>
  24. #include <string>
  25. #include "common/scummsys.h"
  26. /**
  27. * Template function for creating an instance of Type.
  28. */
  29. template<typename BaseType, typename Type>
  30. BaseType *createObject() {
  31. return new Type();
  32. }
  33. /**
  34. * Generic factory for a class and its subclasses.
  35. */
  36. template<typename KeyType, typename BaseType>
  37. class ObjectFactory {
  38. private:
  39. /**
  40. * Function pointer to the object creation function.
  41. */
  42. typedef BaseType *(*CreateFunc)();
  43. /**
  44. * Type used to store registered entries.
  45. */
  46. typedef std::map<KeyType, CreateFunc> RegistryMap;
  47. RegistryMap _registry; ///< Map from an identifier to a creation function.
  48. public:
  49. /**
  50. * Register a new entry.
  51. *
  52. * @param key The key to register the class under.
  53. */
  54. template<typename Type>
  55. void addEntry(const KeyType &key) {
  56. _registry[key] = &createObject<BaseType, Type>;
  57. }
  58. /**
  59. * Creates an instance of some registered class.
  60. *
  61. * @param key The key associated with the desired class.
  62. * @return NULL if the name is not registered, else an instance of the associated class.
  63. */
  64. BaseType *create(const KeyType &key) const {
  65. typename RegistryMap::const_iterator entry = _registry.find(key);
  66. if (entry == _registry.end())
  67. return NULL;
  68. return (entry->second)();
  69. }
  70. };
  71. #endif