Factory Pattern in C++
The factory pattern is part of a class of design patterns called creational design patterns, and the point of the factory pattern is to remove the explicit instantiation of a class out of a user’s code to reduce dependencies.
Let’s talk about some code in a library. Let’s say I had some classes.
So there is a Dog
class, which inherits from Animal
, and a Cat
class,
which also inherits from Animal
.
Let’s take a look at some client code using these classes.
So in this client’s code, the client reads in an integer, and then uses
that integer to determine what dynamic type animalPtr
should be.
What if I decide to add a new animal to my animal kingdom?
Now, the client’s code must be recompiled to account for the new animal
that can be instantiated. The client must add a new
else if
chain to account for the new Bird animal.
As in, the client’s code depends on my
class definitions for my animals.
The solution to this problem is known as the factory pattern. The factory pattern provides a method to instantiate other classes, thus decoupling the responsibility for instantiation from a client’s code.
Of course, in this example, everything is in the same file, but if main
and the library code (Cat
, Dog
, Animal
, AnimalFactory
)
were in separate files, a new class definition derived from Animal
would not require a code change on the client side, because
the responsibility for instantiation is on AnimalFactory
, which
is part of the library code.
Please feel free to email me with any additional questions or concerns at cody@codymorterud.com.