Guest User

factory

a guest
Aug 7th, 2025
17
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | Source Code | 0 0
  1.  
  2. //////////
  3. /// switch case method
  4. //////////
  5. enum object_class
  6. {
  7.     object_class_Light,
  8.     object_class_Mesh,
  9.     object_class_COUNT
  10. };
  11. shared_ptr<Object> makeInstance(object_class ClassEnum)
  12. {
  13.     switch (ClassEnum)
  14.     {
  15.         case object_class_Light: return make_shared(new Light());
  16.         case object_class_Mesh: return make_shared(new Mesh());
  17.     }
  18.     return nullptr; // invalid case, might want to assert here
  19. }
  20.  
  21.  
  22. //////////
  23. /// x-macro method
  24. //////////
  25. #define ExpandEnum(ClassName) object_class_##ClassName,
  26. #define ExpandCase(ClassName) case object_class_##ClassName: return make_shared(new ClassName());
  27. // to add new classes, just add them to this list by name
  28. #define Classes(ExpandMacro) \
  29.   ExpandMacro(Light) \
  30.   ExpandMacro(Mesh)
  31.  
  32. enum object_class
  33. {
  34.   Classes(ExpandEnum)
  35.   object_class_COUNT
  36. };
  37. shared_ptr<Object> makeInstance(object_class ClassEnum)
  38. {
  39.   switch (ClassEnum)
  40.   {
  41.     Classes(ExpandCase)
  42.   }
  43.   return nullptr; // invalid case, might want to assert here
  44. }
  45.  
  46.  
  47. //////////
  48. /// function pointer table method
  49. //////////
  50. enum object_class
  51. {
  52.   object_class_Light,
  53.   object_class_Mesh,
  54.   object_class_COUNT
  55. };
  56. template<typename type>
  57. shared_ptr<Object> createClassTemplate()
  58. {
  59.   return make_shared<type>();
  60. }
  61. typedef shared_ptr<Object> factory_function();
  62. factory_function CreateClassTable[object_class_COUNT]
  63. {
  64.   createClassTemplate<Light>,
  65.   createClassTemplate<Mesh>,
  66.   // make sure the order matches the enum order - you could use the x-macro trick above to generate this in the correct order
  67. };
  68. shared_ptr<Object> makeInstance(object_class ClassEnum)
  69. {
  70.   return CreateClassTable[ClassEnum]();
  71. }
Advertisement
Add Comment
Please, Sign In to add comment