Welcome to the Factory Design Pattern in Java tutorial. Factory Pattern is one of the Creational Design pattern and it’s widely used in JDK as well as frameworks like Spring and Struts.
The factory design pattern is used when we have a superclass with multiple sub-classes and based on input, we need to return one of the sub-class. This pattern takes out the responsibility of the instantiation of a class from the client program to the factory class. Let’s first learn how to implement a factory design pattern in java and then we will look into factory pattern advantages. We will see some of the factory design pattern usage in JDK. Note that this pattern is also known as Factory Method Design Pattern.
Super class in factory design pattern can be an interface, abstract class or a normal java class. For our factory design pattern example, we have abstract super class with overridden toString()
method for testing purpose.
package com.journaldev.design.model;
public abstract class Computer {
public abstract String getRAM();
public abstract String getHDD();
public abstract String getCPU();
@Override
public String toString(){
return "RAM= "+this.getRAM()+", HDD="+this.getHDD()+", CPU="+this.getCPU();
}
}
Let’s say we have two sub-classes PC and Server with below implementation.
package com.journaldev.design.model;
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() {
return this.ram;
}
@Override
public String getHDD() {
return this.hdd;
}
@Override
public String getCPU() {
return this.cpu;
}
}
Notice that both the classes are extending Computer
super class.
package com.journaldev.design.model;
public class Server extends Computer {
private String ram;
private String hdd;
private String cpu;
public Server(String ram, String hdd, String cpu){
this.ram=ram;
this.hdd=hdd;
this.cpu=cpu;
}
@Override
public String getRAM() {
return this.ram;
}
@Override
public String getHDD() {
return this.hdd;
}
@Override
public String getCPU() {
return this.cpu;
}
}
Now that we have super classes and sub-classes ready, we can write our factory class. Here is the basic implementation.
package com.journaldev.design.factory;
import com.journaldev.design.model.Computer;
import com.journaldev.design.model.PC;
import com.journaldev.design.model.Server;
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);
else if("Server".equalsIgnoreCase(type)) return new Server(ram, hdd, cpu);
return null;
}
}
Some important points about Factory Design Pattern method are;
getComputer
is the factory method.Here is a simple test client program that uses above factory design pattern implementation.
package com.journaldev.design.test;
import com.journaldev.design.factory.ComputerFactory;
import com.journaldev.design.model.Computer;
public class TestFactory {
public static void main(String[] args) {
Computer pc = ComputerFactory.getComputer("pc","2 GB","500 GB","2.4 GHz");
Computer server = ComputerFactory.getComputer("server","16 GB","1 TB","2.9 GHz");
System.out.println("Factory PC Config::"+pc);
System.out.println("Factory Server Config::"+server);
}
}
Output of above program is:
Factory PC Config::RAM= 2 GB, HDD=500 GB, CPU=2.4 GHz
Factory Server Config::RAM= 16 GB, HDD=1 TB, CPU=2.9 GHz
getInstance()
methods uses Factory pattern.valueOf()
method in wrapper classes like Boolean, Integer etc.I recently uploaded a video on YouTube for Factory Design pattern, please check it out. Please like and share the video and subscribe to my YouTube channel. https://www.youtube.com/watch?v=J1QU\_R4MQQc
You can download the example code from my GitHub Project.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
how to make ComputerFactory class getComputer generic because in future there could be 100 of implementation class so i need to write 100 if-else statements
- dhanraj
I think the explanation in ‘Factory Design Pattern Advantages’ section is quite verbose. I can tell the advantage of this pattern is simply “reducing repeated codes to choose and instantiate an implementation with arguments you’re having, using the fact there is only one possible implementation of the interface for a combination of arguments or/and for the environment of the machine.” “provides approach to code for interface rather than implementation” and “provides abstraction between implementation and client classes through inheritance” are true, but I think they are just derived results from the reason why you apply this pattern I said above. So I think the first advantage in the section should be what I said above at least.
- Chagndae Park
Pankaj, You have a wide reach and your article make a huge impact on developers. I appreciate your work and dedication that you put to bring this in front of us all. Having said that I want to invite you to partner me in clearing the space and providing the correct Design patterns as they are and not as they occur to you, me or any other author. Lets stick to the original GOF definition. It defines Abstract factory pattern and Factory pattern. I want to point out that the example you have put is neither of that. In the factory pattern , the factory class has an abstract method to create the product and lets the sub classes to create the concrete product. What you have is a static method. also the examples you mentioned as being present in JDK as example of factory method is also not pure factory pattern. They are simply Static Factory methods. Those are not the part of GOF Creational pattern. I want you to edit your post so as Correct information reaches the readers.
- Krishna Kumar
Thanks a lot for the nice content for me!
- Vladimir
Thank you Pankaj for enlightening us with your clear and succinct answer.
- Thomas Lee S
> valueOf() method in wrapper classes like Boolean, Integer etc. Could you explain more about this?
- Jiabin
You said, if we don’t use factory design pattern, Client will be aware of all the instances of the Computer(such as PC, Server), there is no abstraction. Even with factory design pattern, client should be aware of all the instances of the Computer right, else how will the client pass that string(“pc”,“server”) depending on his requirement ?
- Suhas Nayak
It was explained good. Thank you
- Balachandar
Very well descriptive article. Big Thanks !
- Vaibhav Gote
thank’s sir Nice article
- sadiqullah