Abstract factory pattern
Appearance
Insulates client code from object creation by having clients ask a factory object to create an object of the desired abstract type and to return an abstract pointer to the object.
The factory determines the actual concrete type of object to be created, and it is here that the object is actually created (in C++, for instance, via the new operator). However, the factory only returns an abstract pointer to the created conrete object.
Because the factory only returns an abstract pointer, the client code (which requested the object from the factory) does not know - and is not burdened by - the actual concrete type of the object which was just created. In particular, this means:
- The client code has no knowledge whatsoever of the concrete type, not needing to include any headers files or class declarations relating to the concrete type. The client code deals only with the abstract type.
- Adding new concrete types is done by modifying the client code to use a different factory, a modification which is typically one line in one file. This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as simple as changing the singleton object.