Design Pattern Download: The Factory Pattern

Matthew MacFarquhar
2 min readFeb 24, 2022

The factory pattern is a Creational Pattern used in software engineering to establish an extensible structure of how a set of subclasses will behave.

photo by Lenny Kuhne on unsplash

Example

Imagine we want to create multiple car classes for different kinds of cars. We could create an individual Ferrari, Toyota, Tesla, etc… class completely isolated form one another.

Using that methodology…

  • We would not be able to generically reference any car class in an application or store multiple different cars in the same data structure (i.e. List<Car> would need to be List<Ferrari> & List<Tesla> & List<Toyota>)
  • We would also need to duplicate multiple functions (assuming there is a high amount of overlap between Ferrari and Tesla and other cars).

Hence, we use the Factory Pattern to…

  • Use a super class to allow us to do things like Car ferrari = new Ferarri() or List<Car>.
  • We will make the super class abstract so we can implement some common functionality in it so all subclasses can use the same logic without repeating cars.
  • We will leave some functions unimplemented so that they can be specified by the subclasses.

When to use the Factory Pattern?

  • When we do not know what sub-classes we will need to create and what they need to do.
  • When we want to create a set of classes that have some overlapping behavior.

What is the Factory Pattern composed of?

  • The Factory (function that determines which item to create)
  • The Template (an abstract class used for the base item creation)
  • The Items (a set of concrete classes that extend the abstract template class)

Implementation

The Template ⚙️🔧 (Abstract Class)

The Car template implements the generic calculateGas function which will execute the same for all subclasses and a getMpg function which will be implemented by the subclasses.

The Cars 🏎️ 🚗 🚙 (Concrete Classes)

Each type of car implements the getMpg function which allows a specific subclass to determine how much MPG its car will have.

The Factory 🏭 (Function)

The Factory function takes in a parameter for car brand and then creates the appropriate Car subclass.

--

--

Matthew MacFarquhar

I am a software engineer working for Amazon living in SF/NYC.