Factory Design Pattern with a Story
Just think about a factory in real world. Using this factory concept (Factory Pattern) Kiichiro Toyoda in 1937 started a new car factory with the name of “TOYOTA”.
In 1936 the designed their first model “Toyota Modal AA”.
After many many years later they designed a “Toyota Fortuner 2021”
You see, they are totally different models with totally different modifications. Yes, both models manufactured in the same factory. So now we can abstract the basic concept of factory design pattern. Factory need only the requirement and in the factory it design which they received.
Let’s implement this in JAVA.
Modal.java
public interface Modal {
void manufacture();
}
ToyotaModalAA.java
public class ToyotaModalAA implements Modal {
@Override
public void manufacture() {
System.out.println("Manufactured a new model called ToyotaModalAA");
}
}
ToyotaFortuner2021.java
public class ToyotaFortuner2021 implements Modal {
@Override
public void manufacture() {
System.out.println("Manufactured a new model called ToyotaFortuner2021");
}
}
ModalFactory.java
public class ModalFactory {
public Modal getModal(String modalType){
if(modalType == null){
return null;
}
if(modalType.equalsIgnoreCase("ToyotaModalAA")){
return new ToyotaModalAA();
} else if(modalType.equalsIgnoreCase("ToyotaFortuner2021")){
return new ToyotaFortuner2021();
}
return null;
}
}
FactoryPatternDemo.java
public class FactoryPatternDemo {
public static void main(String[] args) {
ModalFactory modalFactory = new ModalFactory();
Modal firstModal = modalFactory.getModal("ToyotaModalAA");
firstModal.manufacture();
Modal secondModal = modalFactory.getModal("ToyotaFortuner2021");
secondModal.manufacture();
}
}
Out Put