Factory Design Pattern in Java for Beginners
The Factory Design Pattern is a creational design pattern used to create objects without exposing the object creation logic to the client. Instead of using the new keyword directly, the client relies on a factory method to get the required object.
Factory Design pattern is used when we have a super class with multiple subclass and based on input , we return the one of the subclasses .
Super class in factory pattern can be an interface , abstract class ,or a normal java class .
Example : Computer.java
package om.rkdigital.school.fact;
public abstract class Computer {
public abstract String getRAM();
public abstract String getHDD();
public abstract String getCPU();
}
Pc.java
package om.rkdigital.school.fact;
public class Pc extends Computer{
private String ram;
private String hdd;
private String cpu;
public Pc(String ram, String hdd, String cpu) {
this.ram=ram;
this.hdd=hdd;
this.cpu=cpu;
}
@Override
public String getRAM() {
// TODO Auto-generated method stub
return this.ram;
}
@Override
public String getHDD() {
// TODO Auto-generated method stub
return this.hdd;
}
@Override
public String getCPU() {
// TODO Auto-generated method stub
return this.cpu;
}
}
Server.java
package om.rkdigital.school.fact;
public class Server extends Computer{
private String ram;
private String hdd;
private String cpu;
public Server(String ram, String hdd, String cpu) {
// TODO Auto-generated constructor stub
this.ram=ram;
this.hdd=hdd;
this.cpu=cpu;
}
@Override
public String getRAM() {
// TODO Auto-generated method stub
return this.ram;
}
@Override
public String getHDD() {
// TODO Auto-generated method stub
return this.hdd;
}
@Override
public String getCPU() {
// TODO Auto-generated method stub
return this.cpu;
}
}
ComputerFactory.java
package om.rkdigital.school.fact;
public class ComputerFactory {
public static Computer getComputer(String type, String ram, String hdd, String cpu) {
if("pc".equalsIgnoreCase(type)) {
return new Pc(ram, hdd, cpu);
}
if("server".equalsIgnoreCase(type)) {
return new Server(ram, hdd, cpu);
}
return null;
}
}
TestFactoryMain.java
package om.rkdigital.school.fact;
public class TestFactoryMain {
public static void main(String[] args) {
Computer pc=ComputerFactory.getComputer("pc","2GB","500MB","2.4GB");
Computer server=ComputerFactory.getComputer("server","2GB","500MB","2.4GB");
System.out.println(pc.getClass());
System.out.println(server.getClass());
}
}