I'm working on the client side of a distributed application that uses what I
call an XML over quasi-HTTP protocol. The client and server are connected
with a single persistent socket and exchange messages that look something
like this:
Content-type: P51Mustang
Content-length: 147
<?xml version="1.0"?>
<P51Mustang>
<Pilot>SGT Yeager</Pilot>
<Fuel units="gallons">600</Fuel>
<Guns caliber="50">6</Guns>
</P51Mustang>
After parsing the HTTP-like headers, the problem boils down to how to
deserialize this object give its name in the Content-type string. In other
words, how to go about creating an object of type class P51Mustang given
that the message is a "P51Mustang" message.
I'm considering a number of ways to do this and wondered if anyone else has
any different ideas. So far I've come up with:
1. A BIG if-else if-else statement that considers all possible object types:
// maintenance nightmare, I know.
if(contenttype == "P51Mustang")
p = new P51Mustang;
2. A "map" object, using STL or another library, that maps a string to a
function pointer to create the appropriate type of object. The map object
must be populated (hard-coded) to map the names of the various types of
objects to the appropriate function pointers before being used. Another
maintenance nightmare, much like the BIG if-else if- else statement above.
Use would go something like this:
typedef IncomingMessage* (*fpCreateMsg)( );
void *fpv = 0;
if(map.Lookup(contenttype, fpv))
{
// fpv now points to a function will create the appropriate object
type.
fpCreateMsg fp = (fpCreateMsg)fpv; // now we have a function pointer
that can be invoked.
IncomingMessage *pMessage = (*fp)( );
// We now have an uninitialized P51Mustang object, although the
calling object only knows that it's an IncomingMessage.
// pMessage can be use to initialize the object with the XML here.
// Getting the right thing to happen next is a double-dispatch
problem, but I don't want to get into that here.
}
3. Use a DLL (running on Windows) to find the appropriate function based on
contenttype. Easier maintenance, but might be slower than above methods:
void *fpv = GetProcAddress(hModule, contenttype);
if(fpv)
{
// we can proceed as in 2. above if Lookup succeeds.
4. A combination of 2. and 3. above where the function pointer is retrieved
from the DLL if it is not found in the map and then stored in the map for
later (and faster) use. Easier maintenance than 1. and 2. above, and
probably pretty fast.
Any other ideas? I realize that there are many middleware solutions as well
as commercially available and shareware libraries that deal with such object
deserializations over a network, but unfortunately I am not able to use any
of these do to management decisions.
Thanks!
Mike