The Factory pattern
The problem we are faced with, that is, how to decide at runtime to create an object of a particular type, is obviously a very common design problem. Design patterns are the solutions for just such problems, and there is a pattern for this problem as well—it’s called the Factory pattern. The Factory pattern is a creational pattern, and it provides solutions for several related problems—how to delegate the decision of which object to create to a derived class, how to create objects using a separate factory method, and so on. We will review these variations of the Factory pattern one by one, starting with the basic factory method.
The basics of the Factory method
In its simplest form, the factory method constructs an object of a type that’s specified at runtime:
class Base { ... }; class Derived : public Base { ... }; Base* p = ClassFactory(type_identifier, ... arguments );
How do we identify at runtime which object to create...