Design Patterns in Ruby: Abstract Factory

A clear example of the Abstract Factory pattern

D. L. Jerome
2 min readDec 18, 2016

A clear example

The intent

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

“Provide an interface for creating families of related or dependent objects without specifying their concrete classes.”

The example

In the example below, we discover that just as the Factory Method pattern is merely the Template Method pattern as applied to object creation, so too is the Abstract Factory pattern the Strategy pattern as applied to object creation. The Abstract Factory pattern aids in the creation of sets of compatible objects which can be swapped out for one another.

Some Tidbits

Composition vs Inheritance

As with the Strategy pattern, composition is used to decouple set of compatible objects, what those objects are and how those objects are created, from the class that uses those objects.

When to use the Abstract Factory pattern

You should use the Abstract Factory pattern whenever you have a system which should remain independent of how its objects are created, composed, and represented.

You should also use the Abstract Factory pattern in cases where related families of objects are created and designed to be used together and you need to enforce that design.

The Abstract Factory pattern may also be used to reveal the interfaces of families of objects, but conceal their implementations.

Benefits of the Abstract Factory pattern

The Abstract Factory pattern makes it easy to create and manage families of objects. It also makes it easy to to exchange one family of objects for another, as they share an interface. It promotes consistency across the product families, leading to a pleasing, though more rigid, design.

Going deeper

The Abstract Factory pattern is just one of several patterns dealing with the creation of objects in code. To learn more, check out the seminal work on Design Patterns: The GOF Design Pattern book.

--

--