I've got an incoming XML message. One of the fields inside it tells me what sort of message has to be generated from it, there are currently 5 different ones I've got to deal with, so I've got 1 base class (with a build method) & 5 subclasses for this. I can't think of a nice way to handle the subclass constructors though. I've thought of 2 variations which are basically the same, but both are pretty bad. There has to be a clever way of doing it but I don't know what it is.
1. declare msg of class baseclass if xml says its baseclass 1 then msg = new baseclass1 () else if msg says its baseclass2 then msg = new baseclass2 () else if .... else raise error as unrecognised message, return end if; msg.build ();
2. have a hash table of message codes to integers returning 0 if not found switch (on the int returned from the hash look up) case 1 : msg = new baseclass1 () case 2 : msg = new basseclass2 () ... default : raise error as unrecognised message, return
end switch; msg.build ();
With both of these, this code has to change whenever a new subclass is introduced, which is what I want to avoid. Any ideas? :confused