Design Patterns — Zero to Hero — Factory Pattern (Simple Factory and Factory Method)

The Factory Method Pattern encapsulates to object creation by letting sub-classes to decide what objects to create at run-time (while execution).

Class() obj = new Class();

Before moving into the explanation part we need to have a clear understanding of concrete class.

A class that has an implementation for all of its methods is called Concrete class. They cannot have any unimplemented methods. The concrete class can extend the Abstract class or an interface as long as its implements all the methods of those too. Simply, we can say that all classes which are not Abstract class are considered as Concrete classes.

Simple Factory Pattern

public interface IMobile {
void sendMessage();
}
public class Samsung implements IMobile{    @Override
public void sendMessage() {
System.out.println("Samsung Selected");
}
}
public class iPhone implements IMobile {@Override
public void sendMessage() {
System.out.println("iPhone Selected ");
}
}
public class App {     public static void main(String[] args) {         IMobile mob1 = new Samsung();    
mob1.sendMessage();
IMobile mob2 = new iPhone();
mob2.sendMessage();
}}
public class MobileFactory {       IMobile mobile = null;       //getType method will return IMobileobject creation according              to the parameter passsed       IMobile getType(String str) {             if(str.equals("Samsung")) {
mobile = new Samsung();
}else if(str.equals("iPhone")) {
mobile = new iPhone();
}
return mobile;
}
}
public class App {
public static void main(String[] args) {
MobileFactory mobfactory = new MobileFactory(); mobfactory.getType("Samsung").sendMessage();;
}
}

Factory Method Pattern

public abstract Brands{       public Equipment orderEquipment(String equipment){
Equipment equip;
equip = getDetail(equipment);
return equip; } protected abstract Equipment getDetail(String brandName)}
public Canon extends Brands{     protected Equipment getDetail(String equipment){
Equipment equip = null;
if(equipment.equals("DSLR")){
equip = new CanonDSLR();
}else if(equipment.equals("Scanner")){
equip = new CannonScanner();
}else if(equipment.equals("Printer")){
equip = new CanonPrinter()
}
return equip;
}
}
public interface Equipment{        void printBrand();}
public class CanonDSLR implements Equipment{    @Override
public void printBrand() {
System.out.println("Canon DSLR Selected");
}
}
public class App {    public static void main(String[] args) {         Brands canon1 = new Canon();         Equipment equip1 = canon1.getDetail("DSLR");         equip1.printBrand();    }}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store