0

I am looking for a way to load a specific class/subclass type based on JSON input. For example, I have the following JSON file

"type" : "RenderVertices"
"RenderComponent": {
  "vertex": {
    "xcoords" : [0, 1, 1, 0]
    "ycoords" : [0, 0, 1, 1]
  
  }

  "texture": {
    "name" : "testtex"
    "texcoordsx" : [0, 1, 1, 0]
    "texcoordsy" : [0, 0, 1, 1]
  }
  
  "color" : {
    "color_r": [0, 0, 0, 0]
    "color_g": [0, 0, 0, 0]
    "color_b": [0, 0, 0, 0]
    "color_a": [0, 0, 0, 0]
  }
  
  "type": "quads"
}

In my program I have two classes, a base class and a subclass

class RenderComponent;

and

class RenderVertices : public RenderComponent

I will eventually have a large number of classes that inherit from RenderComponent, and I would like be able to construct a specific object subclass (in this case, RenderVertices) based on the "type" specifier in the JSON file. I understand how to do this using some sort of factory function with a switch statement, but this requires adding a new entry for every subclass type I make, which I would like to avoid if possible. What is the most scalable way to accomplish this (and by scalable I mean least required code modifications per new subclass created)?

I am using nlohmann::json to parse my JSON file (https://github.com/nlohmann/json)

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • I think this is a pretty clear-cut use case for a factory function, as you've suggested. If you change your data format, it makes sense that you should have to change the parsing factory as well. Changing existing code isn't bad; changing *irrelevant* code is bad, and in your case, the code that would have to be changed in a factory function is *very* relevant to the act of parsing JSON. – Silvio Mayolo Feb 21 '21 at 22:06
  • _"What is the most scalable way to accomplish this"_ _Scalable_ is probably the wron term here. Sounds more like a concern about maintainability and extensibility. Besides the simple one, there are more sophisticated [_Factory Patterns_](https://sourcemaking.com/design_patterns/creational_patterns) (like e.g. _Abstract Factory_), which are meant to help you in realizing more complex and flexibility demanding scenarios. The major point is using well defined seperate interfaces, for different aspects of your class hierarchies (which classes have what in common, to share via virtual functions). – πάντα ῥεῖ Feb 21 '21 at 22:19

0 Answers0