During coding I frequently encounter this situation:
- I have several objects (
ConcreteType1
,ConcreteType2
, ...) with the same base typeAbstractType
, which has abstract methodssave
andload
. Each object can (and has to) save some specific kind of data, by overriding thesave
method. - I have a list of
AbstractType
objects which contains variousConcreteTypeX
objects. - I walk the list and the
save
method for each object.
At this point I think it's a good OO design. (Or am I wrong?) The problems start when I want to reload the data:
Each object can load its own data, but I have to know the concrete type in advance, so I can instantiate the right ConcreteTypeX
and call the load
method. So the loading method has to know a great deal about the concrete types. I usually "solved" this problem by writing some kind of marker before calling save
, which is used by the loader to determine the right ConcreteTypeX
.
I always had/have a bad feeling about this. It feels like some kind of anti-pattern...
Are there better ways?
EDIT: I'm sorry for the confusion, I re-wrote some of the text. I'm aware of serialization and perhaps there is some next-to-perfect solution in Java/.NET/yourFavoriteLanguage, but I'm searching for a general solution, which might be better and more "OOP-ish" compared to my concept.