Member-only story
Understanding the Factory Method Design Pattern
Decouple the build code respecting the open-closed principle (OCP)

There are 23 classic design patterns described in the book “Design Patterns: Elements of Reusable Object-Oriented Software.” These patterns provide solutions to particular problems that are often repeated in software development.
In this article, I’m going to describe how the factory method pattern works and when it should be applied.
Factory-Method: Basic Idea
“The factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method — either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes — rather than by calling a constructor”
“Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.”
— Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, “Design Patterns: Elements of Reusable…