Creational Design Patterns

Factory Method

Intent: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Also Known As: Virtual Constructor


A factory method (virtual constructor) is really a wrapper for a constructor, implemented as a virtual function. Typically, it returns a pointer to a newly created object. In case of subclassing, such a function can be overridden so that subclass type objects are returned.

The general principle of proper object oriented design with class hierarchies is that client code should always talk ONLY TO THE BASE CLASS. Such a design avoids ifs/switches that check hard-coded class names, resulting in un-extendible code. For ordinary member functions this requirement is easily achieved using virtual member functions. But creating new objects that belong to various levels of a class hierarchy with generic client code (i.e. one without hard coded class names and accompanying ifs/switches) can be achieved only through design patterns, like the Factory Method (and the Abstract Factory).

Note: a real constructor cannot be virtual. First, constructor names are set by the class name, so cannot be overriden. Second, trying to declare a constructor virtual results in a compile error. The problem with using actual (non-virtual) constructors is hard-coding class names. Code with hard-coded class names is hard to change. This problem is solved by the Factory Method design pattern.