Factory design pattern — Java

Factory pattern tutorial

Erwan LE TUTOUR
Javarevisited
2 min readFeb 11, 2021

--

Definition of the Factory pattern

In class-based programming, 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.

Where to use the Factory pattern

  • When a class doesn’t know what sub-classes will be required to create
  • When a class wants that its sub-classes specify the objects to be created.
  • When the parent classes choose the creation of objects to its sub-classes.

UML example

Implementation of the Factory Pattern

We are going to create a Human abstract class and then the different periods of age that will implement it, then we will create the factory that will generate it.

The human abstract class

The implementations

Each implementation overrides the getAge() method to return a random int that will correspond to the age period.

The factory

Now we can create the factory that will generate a Human based on the given information, here we will use an enum to be sure that we don’t pass the nonexisting value to the factory

now we can generate our humans using the factory

Usage

that will give an output like the following one :

Here are other design pattern articles you may like

--

--