The IntroductionObject factories are one of those extremely useful but often times overlooked constructs in programming. To put it simply, object factories are like virtual functions but instead of dynamically choosing which function gets executed at runtime, object factories dynamically choose which class gets instantiated at runtime. If you don't have a good understanding of object factories (sometimes also called pluggable factories) then I highly recommend reading Industrial Strength Pluggable Factories and Why Pluggable Factories Rock My Multiplayer World before continuing this article. All set? Good, then let's get started. The NeedWe already stated that object factories delay the choice of which object is created until runtime. Before we go any further, it might be beneficial to list some examples of when need to delay the choice until runtime. Here are just a few:
There are of course many other instances where object factories are useful, but I won't bore you with them all. Instead, let's get on to something more exciting. The ImplementationOK, now that we know when object factories are useful it's time to figure out how to actually implement one. Below we have an object factory in its most simplistic form. class ShapeFactory { public: Shape *Create(int shape) { if (shape == SQUARE) return new Square; else if (shape == CIRCLE) return new Circle; else if (shape == TRIANGLE) return new Triangle; } }; Not much to it, really. The ShapeFactory class has a Create method which allows us to create a Square, Circle, or Triangle class simply by passing the appropriate unique identifier, in this case an integer. This integer value could be hard-coded or passed in from an outside source such as a TCP/IP stream, a script file, or from the player himself. The syntax to use our sample object factory class is simple enough: ShapeFactory shape_factory; Shape *shape1 = shape_factory.Create(TRIANGLE); Shape *shape2 = shape_factory.Create(SQUARE); |
|