We'll learn what Factory Pattern are, how to write a real life example, and how to use them.
Create an interface Model.java
Create concrete classes implementing the same interface.
public class GalaxyS20 implements Model {
System.out.println("build() method Inside GalaxyS20.");
Create a Factory to generate object of concrete class based on given information.
public class ModelFactory {
public Model getModel(String modelType){
if(modelType.equalsIgnoreCase("GalaxyS20")){
} else if(modelType.equalsIgnoreCase("GalaxyA50")){
} else if(modelType.equalsIgnoreCase("GalaxyM32")){
Use the Factory to get object of concrete class by passing an information such as type.
public class FactoryPattern {
public static void main(String[] args) {
ModelFactory modelFactory = new ModelFactory();
Model model1 = modelFactory.getModel("GalaxyS20");
Model model2 = modelFactory.getModel("GalaxyA50");
Model model3 = modelFactory.getModel("GalaxyM32");
Verify the output.
build() method Inside GalaxyS20.
build() method Inside GalaxyA50.
build() method Inside GalaxyM32.