Author image

Factory Design Pattern


Definition:

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

Description

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).

You might wonder, what is the usefulness of this design pattern?

Well, that's a legitimate question. I use the Factory pattern, when all the potential classes I'd like to create are in the same subclass hierarchy, but...

1