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

public interface Model {
    void build();
}

Step 2

Create concrete classes implementing the same interface.

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

Step 3

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

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.

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.

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