DEV Community

Erwan Le Tutour
Erwan Le Tutour

Posted on

1

Factory design pattern — Java

design-pattern

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

package main.factory;
abstract class Human {
protected int age;
abstract int getAge();
public void print(){
System.out.println("==============================");
System.out.println("age : " + getAge());
System.out.println("==============================");
}
}
view raw Human.java hosted with ❤ by GitHub

The implementations

package main.factory;
import java.util.Random;
public class Child extends Human {
@Override
int getAge() {
Random r = new Random();
return r.nextInt((18 - 1) + 1) + 1;
}
}
view raw Child.java hosted with ❤ by GitHub
package main.factory;
import java.util.Random;
public class Parent extends Human{
@Override
int getAge() {
Random r = new Random();
return r.nextInt((55 - 20) + 1) + 20;
}
}
view raw Parent.java hosted with ❤ by GitHub
package main.factory;
import java.util.Random;
public class GrandParent extends Human{
@Override
int getAge() {
Random r = new Random();
return r.nextInt((99 - 55) + 1) + 55;
}
}

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

package main.factory;
public enum HumanPeriodEnum {
CHILD, PARENT, GRANDPARENT;
}
package main.factory;
public class HumanFactory {
public Human getHuman(HumanPeriodEnum period){
switch (period){
case CHILD:
return new Child();
case PARENT:
return new Parent();
case GRANDPARENT:
return new GrandParent();
}
return null;
}
}

now we can generate our humans using the factory

Usage

package main.factory;
public class FactoryMain {
public static void main(String[] args) {
HumanFactory factory = new HumanFactory();
factory.getHuman(HumanPeriodEnum.CHILD).print();
factory.getHuman(HumanPeriodEnum.PARENT).print();
factory.getHuman(HumanPeriodEnum.GRANDPARENT).print();
}
}

that will give an output like the following one :
==============================
age : 8
==============================
==============================
age : 49
==============================
==============================
age : 99
==============================
Enter fullscreen mode Exit fullscreen mode

Here are other **design pattern articles **you may like
7 Best Online Courses to learn Object-Oriented Design Pattern in Java
10 OOP Design Principles You Can Learn in 2021
7 Best books to learn Design Patterns for Java Programmers

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

Top comments (0)

Sentry image

Make it make sense

Only the context you need to fix your broken code with Sentry.

Start debugging →

👋 Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay