Abstract Factory

A factory is useful for when we want to create instances of objects at runtime - where the instances have a common base-class.
A very basic example of a factory, usually used when you have a small enum with only a few classes. In this case, it is a simple plain-C function.

 

A more advanced example, where client can register their own creation function. This can be useful when you have a closed-source API, which can be extended by clients, so your factory will need to be able to handle client classes which were unknown the moment you compiled your library.
Basically on libary level, we define a class CarFactory, which only function is to create a new instance of another class. Which class is instantiated is hardcoded. Now we will need to define a derived class of CarFactory, for each new car we add. In the example below, we created a SubFactory, which can create instances of the class Suv. Note that the SuvFactory gets a function which identifies which type can be created.
Now we can register the derived classes of CarFactory. They use their getType to add themselves into a map for quick lookup. Now its easy to create new instances; we call the ConcreteFactory with the type. The ConcreteFactory does a lookup and in case it find a match, it calls the createObject.
Note that in the example below, unlike in the above example, a string is used for simplicity. This can easily be changed to a unsigned int, or maybe a hash of a string. see the following C++ sourcecode

 

Now assuming we need multiple (unrelated) factories. It would be good if we would have to above code as a template. Here is a start of the implementation. Remaining implementation is left as an exercise to the reader.

 
JSN Teki template designed by JoomlaShine.com