Design Patterns in Ruby: Factory Method

A clear example of the Factory Method pattern

D. L. Jerome
2 min readDec 17, 2016

A clear example

The intent

According to the GoF, the intent of the Factory Method pattern is to:

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

The example

In the example below, we discover that the Factory Method pattern is actually the Template Method pattern as applied to the problem of object creation. A factory method differs from a template method in that it is explicitly responsible for manufacturing an object. If it does not manufacture an object, then it is not a factory method. The example here is meant to be self-descriptive, owing to a liberal sprinkling of comments.

Some Tidbits

When to use the Factory Method pattern

You should use the Factory Method pattern when you have a class that can’t anticipate the class of objects it must create. Or, when you want subclasses to specify which objects should be created.

Why should you use the Factory Method pattern?

The Factory Method pattern decouples a class from the objects it creates, creating a separation between what an object is and how it is used. That creates a more flexible, extensible system. The Factory Method pattern helps us to conform to the Open-Closed Principle: “Software entities should be open for extension, but closed for modification.”

Parameterized factory methods

There is an alternate form of the standard factory method, the parameterized factory method. In this variant of the pattern, a factory method can create multiple kinds of objects. This is accomplished by passing a parameter into the factory method. The parameter passed in identifies which type of object to create.

Inheritance and the Factory Method pattern

The Factory Method pattern relies on subclasses and therefore inheritance. All of the usuals trade-offs when choosing to design with inheritance apply.

How many subclasses is too many?

The usefulness of the Factory Method pattern will begin to degrade if the number of creational variants needed exceeds a certain threshold.

Going deeper

The Factory Method pattern is one of several useful creational patterns. To learn more, check out the seminal work on Design Patterns: The GOF Design Pattern book.

--

--