Factory Design Pattern in java

Bavatharany Mahathevan
2 min readJan 15, 2022


The Factory design pattern is also the most commonly used design pattern and comes under the creational design pattern type. This design pattern is slightly the same as the Singleton design pattern, but, in the factory design pattern, we pass the parameter to create an instance, but in the singleton design pattern, we do not pass the parameter to create an instance. To more understand the singleton design pattern, you can refer to my singleton design pattern article also.


We will look at an example of the Factory Design Pattern implemented in Java. In the below example, we will learn how to use the Factory pattern in different message types.

There are mainly three types of vaccine types are available in Sri Lanka currently Sinopharm, Pfizer, AstraZeneca.Let's create a small implementation based on it.

First, we can create one interface or abstract class Vaccine which has an abstract method named vaccinate().

we can create particular vaccine type classes, so that can implement the Vaccine interface and implement the vaccinate() method according to that vaccine type.

Here, Three types of vaccine-type classes, Sinopharm, Pfizer and AstraZeneca respectively.

The next step is to define the Factory class named VaccineFactoryBuilder, in this case, which is a VaccineFactoryBuilder.

The static getvaccineType() method will create a particular vaccine type instance based on the passed parameter.

The next step is to create the main class. The Factory class VaccineFactoryBuilder to pass the vaccine type which user enters.

The new particular instance will execute its method.

Output :

When can the factory design pattern be used?

  • when a class can not predict, which type of object needs to be created
  • when a class depend on its subclass to create an instance at runtime
  • When we want to work with the predefined library classes like Numberformat, Calander etc.

Reference :




Bavatharany Mahathevan