Create an interface Model.java
public interface Model {
void build();
}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.");
}
}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;
}
}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();
}
}Verify the output.
build() method Inside GalaxyS20.
build() method Inside GalaxyA50.
build() method Inside GalaxyM32.