I am looking for a good way of persisting arbitrary subclasses.
I am writing objects asDictionary to json upon save, and init(json) them back upon load. The structure is Groups that have Units of different kind. The Group only knows its units as something implementing UnitProtocol.
The subclasses UA etc of Unit has the exact same data as a Unit. So data wise, the asDictionary and init(json) fits well in Unit. The subclasses only differ in logic. So when restoring them from file, I believe it has to be the exact subclass that is initialized.
(Bad) Solutions I thought of
- Letting every group know that it can have Units of different subclasses by not holding them as
[UnitProtocol]only, but also as[UA],[UB], etc, that can saved separately, restored by their respective sub inits, and be merged into a[UnitProtocol]upon init. - Store subunits with their classname and create a
Unit.Init(json)that somehow is able to pass down the initialization depending on subtype. - ?? Still thinking, but I believe there has to be something I can learn here to do this in a maintainable way without breaking the single responsibility policy.
