Author image

Factory Design Pattern



Define an interface for creating an object, but let subclasses decide which class to instantiate.


The factory function is used to create an object of any type of subclass of a base class.
Instead of creating objects like this:

ObjectType* o = new SubObjectType{args};

we create them like this:

ObjectType* o = newSubObjectType{args};

Where newSubObjectType is the factory function's name. Yes, the factory is nothing more but a construction function for objects; it's typically a global/free function (not a method).


  • Create your class hierarchy.
  • The factory function returns one of several possible classes that share a common base class.

The factory design pattern makes a, sort of, virtual constructor possible as you'll notice in the code.

When to use it?

  • When we don't want to expose the object's creation logic, or any of the concrete subclasses to the client.
  • When all the potential classes are in the same subclass hierarchy, but we don't know ahead of time (at compile time) exactly what specific class we need.

Abstract Factory

The related abstract factory design pattern is again a function which is used to create an object of any type of related, or dependent subclasses. In other words it creates an object among a family of similar classes. I've never used this one but I referred to it for the sake of completion.

I used Windows 8.1 x86_64, Visual Studio 2017 to build the project.


Github repository link.