Factory Design Pattern
design-patternjava
Jun 25, 2022

We'll learn what Factory Pattern are, how to write a real life example, and how to use them.

Step 1

Create an interface Model.java

Model.java

public interface Model {
void build();
}

Step 2

Create concrete classes implementing the same interface.

GalaxyS20.java
/GalaxyA50.java
/GalaxyM32.java

public class GalaxyS20 implements Model {
@Override
public void build() {
System.out.println("build() method Inside GalaxyS20.");
}
}

Step 3

Create a Factory to generate object of concrete class based on given information.

ModelFactory.java

public class ModelFactory {
public Model getModel(String modelType){
if(modelType == null){
return null;
}
if(modelType.equalsIgnoreCase("GalaxyS20")){
return new GalaxyS20();
} else if(modelType.equalsIgnoreCase("GalaxyA50")){
return new GalaxyA50();
} else if(modelType.equalsIgnoreCase("GalaxyM32")){
return new GalaxyM32();
}
return null;
}
}

Step 4

Use the Factory to get object of concrete class by passing an information such as type.

FactoryPattern.java

public class FactoryPattern {
public static void main(String[] args) {
ModelFactory modelFactory = new ModelFactory();
Model model1 = modelFactory.getModel("GalaxyS20");
model1.build();
Model model2 = modelFactory.getModel("GalaxyA50");
model2.build();
Model model3 = modelFactory.getModel("GalaxyM32");
model3.build();
}
}

Step 5

Verify the output.

console

build() method Inside GalaxyS20.
build() method Inside GalaxyA50.
build() method Inside GalaxyM32.

← Back

2022 © Rahat Hosen