• Advertisement
Sign in to follow this  
  • entries
    7
  • comments
    6
  • views
    6571

Dihydrogen monoxide is good for you

Sign in to follow this  

500 views

If you haven't already, I recommend you read the article"Creating a Generic Object Factory" by Robert Geiman. One of the iterations of the object factory he created was very similar to the factory code I had written, but I liked his implementation a bit better, so I'm using something nearly identical to his code.

The only major difference is that I opted to make each factory into a singleton. If you want a factory of type Shape, you could obtain it like so:

ObjectFactory *pShapeFactory = ObjectFactory::Instance();

And if you wanted to register a Square to be creatable as "square":

pShapeFactory->Register("square");

And finally, creating a square:

Square *pSquare = (Square*)pShapeFactory->Create("square");

Pretty simple, really. For more information, read the article, and have a look at my factory code. (I'll link to it below.)

Now, what does this have to do with the XML stuff I've been talking about? Well, I wanted to be able to take a look at the TiXmlElement's value (the name of the tag) and immediately know what kind of object to create. Without a huge if/then tree or switch statement that had knowledge of every single type I might ever create, that was a problem. This is no problem if I use a generic object factory.

We just need a factory of the base type, which is XmlObject, now that all my XML ready classes support the same interface, then register each type to the name I'm using for the tag, and away we go.

ObjectFactory *pXmlObjectFactory = ObjectFactory::Instance();
pXmlObjectFactory->Register("level");
pXmlObjectFactory->Register("enemy");

XmlObject *pUnknownXmlObject = pXmlObjectFactory->Create(xmlElement.Value());




The problem, now, is that I have no idea what I'm pointing to. Is it a Level? Is it an Enemy? Is it something else registered in some dll code somewhere? What do I do with whatever I've just loaded? How I'm handling the problem is some very simple run time type information. (Just a "what kind of object are you?" function. Which is not in the code I've uploaded. The xmltest.cpp is braindead simple.)

If anybody has any ideas for a better way to do this, I'd love to hear it. (That's a major reason for me sharing it.)

Here's the latest versions of everything:
factory.h
xmlutil.h
xmlutil.cpp
xmltest.cpp

On a happy note, completely unrelated to these entries, I asked my girlfriend to marry me yesterday. She said yes. Happy happy!
Sign in to follow this  


1 Comment


Recommended Comments

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement