Tutorial

Factory Design Pattern in Java

Published on August 3, 2022
author

Pankaj

Factory Design Pattern in Java

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.

Factory Design Pattern

factory design pattern, factory design pattern in java, factory pattern, factory method pattern, factory pattern example 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.

Factory Design Pattern Super Class

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();
	}
}

Factory Design Pattern Sub Classes

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;
	}

}

Factory Class

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;

  1. We can keep Factory class Singleton or we can keep the method that returns the subclass as static.
  2. Notice that based on the input parameter, different subclass is created and returned. getComputer is the factory method.

factory pattern java, factory pattern, factory design pattern, factory pattern class diagram 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

Factory Design Pattern Advantages

  1. Factory design pattern provides approach to code for interface rather than implementation.
  2. Factory pattern removes the instantiation of actual implementation classes from client code. Factory pattern makes our code more robust, less coupled and easy to extend. For example, we can easily change PC class implementation because client program is unaware of this.
  3. Factory pattern provides abstraction between implementation and client classes through inheritance.

Factory Design Pattern Examples in JDK

  1. java.util.Calendar, ResourceBundle and NumberFormat getInstance() methods uses Factory pattern.
  2. valueOf() method in wrapper classes like Boolean, Integer etc.

Factory Design Pattern YouTube Video Tutorial

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.

Learn more about our products

About the author(s)

Category:
Tutorial

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.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 10, 2014

Some body asked me that Why do we have to implement singleton pattern when we have static. And here in your post you say that either we can use static method or implement it as Singleton. Can you please detail on this?

- Siva

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
May 16, 2016

May be its a late reply, but worth share thought here. Factory classes(In general design patterns) are meant for maintainability and re-usability. Factory pattern states that, the objective of this pattern is to decouple the object instantiation from the client program. And this can be achieved either by static method or singleton factory class. Why we use singleton pattern when we have static? we use “static” when a piece of code/data same across all instances of a class OR important piece of code that needs to be executed even when class is not instantiated OR instantiation is not required. Question here is, how to make outer class itself static? the answer is “Singleton Pattern”. The “singleton pattern” is a mechanism, which gives the flexibility to reuse the same instance of a class(avoid multiple instantiation of a class when it is not required OR execute mandatory functionality only once) OR have the single instance to achieve the expected functionality. This can be achieved by using static + additional checks on the pre-existence of the instance(of self). Ex: Thread pool.

- JavaBee

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 11, 2016

Good answer!!!

- robothy

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    February 26, 2017

    Very good answer… Thank You

    - RazorEdge

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      February 24, 2015

      Thanks for the clear explanation. I have one doubt here in Factory pattern. We have two concrete classes implementing the interface/Abstract class whose instances are created inside Factory class.But, instead of below line Computer pc = ComputerFactory.getComputer(“pc”,“2 GB”,“500 GB”,“2.4 GHz”); we can also use Computer pc=new PC(“pc”,“2 GB”,“500 GB”,“2.4 GHz”); to get new instance of PC. Then what is the advantage of using ComputerFactory.getComputer() method on the client side directly.?

      - vamshi

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 22, 2015
      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 5, 2016

      That’s why it’s called an creation all design pattern cause then we don’t have to dirty our code keeping the instance creation all logic here and there cause we have implanted a factory out there which is just doing it for us you just name it…name the object and it’s ready for you…

      - Ajay

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 14, 2017

        Thats because u will be bound to the object, ie if you create Computer pc=new PC(“pc”,”2 GB”,”500 GB”,”2.4 GHz”) u will always get the instance of PC and it would be hardcoding, So if you use factory you wil not worry of the implementation u will always get the object of reference Computer.

        - Avinash Nayak

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          June 3, 2016

          Now i found the perfect article for Design pattern. Thanks Pankaj

          - panky031

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            August 11, 2016

            Nice article !!!

            - Gani Victory

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              October 6, 2016

              It seems to me that you’re showing what is called a simple factory with ComputerFactory; It is not the Factory Method Pattern. The client TestFactory delegates the creation to another class which it is composed with. If you want to implement the Factory Method Pattern,: 1. ComputerFactory should define an asbtract method getComputer(String ram, String hdd, String cpu) 2. ComputerFactory should have two subclasses PCFactory and ServerFactory.which implements the superclass abstract method to return either a PC or a server 3. The client should be given one of the two concrete factories and call the factory method to get PC or servers, depending which one was instanciated

              - JocelynL

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              February 26, 2017

              yes , i agree. the article is about simple factory not factory . But still a nice article.

              - catherine

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              May 3, 2018

              Could you please reply back with actual factory pattern example in your own explanatroy words…

              - Vijay Kambala

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                March 23, 2017

                yes absolutely you are right. It is not factory method pattern.

                - Vinod Kumar

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  June 15, 2017

                  This is a factory (factory method ) pattern, if you make factory abstract then it becomes abstract factory pattern

                  - ravi

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    May 7, 2017

                    I am relatively new to design patterns but I need to ask this question. What if we need to add another subclass of computer say Laptop to the application.? Does this mean we will have to modify the computer factory class? This looks like violating the OO principle which says classes should be closed to modification but open to extension.

                    - Stephen Ubogu

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      August 23, 2017

                      Yes. Its very nice article about simple factory covers basic concepts.

                      - Vishal

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        September 8, 2017

                        Hi, is there a place in which I can download all the source code for the several design pattern examples. These are great examples, but I have to copy-paste each single text box into Intellij, and it is very cumbersome. Thank you very much, and congratulations for such good material.

                        - Luis Cunha

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          November 16, 2017

                          It’s a very good tutorial. But I have a doubt, You mentioned Calendar#getInstance() as factory pattern implementation. But in this there is a small difference right? There is no separate factory class. The super class Calendar itself is acting as the factory class. Does an implementation like this have any advantage or disadvantage?

                          - Prashanth

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            January 24, 2018

                            Where below are implemented import com.journaldev.design.abstractfactory.PCFactory; import com.journaldev.design.abstractfactory.ServerFactory;

                            - BkOfc

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            January 24, 2018

                            Sorry, that came out while copying the code from my Eclipse editor by mistake. Those imports are useless, I have removed them from above code.

                            - Pankaj

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              February 16, 2018

                              Learned some new stuff with very detailed information.

                              - Daniel

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                February 21, 2018

                                Quick and easy tutorial, thanks.

                                - Chris

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  March 30, 2018

                                  It’s Nice Explanation Learnt new things more it’s best practice and understanding

                                  - Srinivasa…

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    April 4, 2018

                                    I understand that there’s always a benefit to get the instance of a class using the provided factory implementation. How can I force users to compulsorily use the factory implementation to get the instance, instead of getting away creating an instance directly using new operator of the actual class? i.e. How can I force people to use ServerFactory.getInstance() instead of new Server()?

                                    - Nirav Khandhedia

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    April 10, 2018

                                    You can make Server Class as an abstract class.

                                    - Geeks

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      June 3, 2018

                                      very nice tutorial, easy to understand!

                                      - wade

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        July 24, 2018

                                        Very weel explained! Thank you!

                                        - Jaleel

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          August 21, 2018

                                          Very helpful artical. Thank you.

                                          - supriya

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            January 2, 2019

                                            Thanks for sharing

                                            - 7hills

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              February 27, 2019

                                              how do i implement a factory to store my data and call it inside my unit tests?

                                              - Justin

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                March 15, 2019

                                                Thanks for sharing.

                                                - Yeremia Maroutian

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  March 16, 2019

                                                  thank’s sir Nice article

                                                  - sadiqullah

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    August 15, 2019

                                                    Very well descriptive article. Big Thanks !

                                                    - Vaibhav Gote

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      September 30, 2019

                                                      It was explained good. Thank you

                                                      - Balachandar

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        November 10, 2019

                                                        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

                                                          JournalDev
                                                          DigitalOcean Employee
                                                          DigitalOcean Employee badge
                                                          November 16, 2019

                                                          > valueOf() method in wrapper classes like Boolean, Integer etc. Could you explain more about this?

                                                          - Jiabin

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            January 20, 2020

                                                            Thank you Pankaj for enlightening us with your clear and succinct answer.

                                                            - Thomas Lee S

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              June 6, 2020

                                                              Thanks a lot for the nice content for me!

                                                              - Vladimir

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                July 15, 2020

                                                                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

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  September 19, 2020

                                                                  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

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    April 20, 2021

                                                                    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

                                                                      Try DigitalOcean for free

                                                                      Click below to sign up and get $200 of credit to try our products over 60 days!

                                                                      Sign up

                                                                      Join the Tech Talk
                                                                      Success! Thank you! Please check your email for further details.

                                                                      Please complete your information!

                                                                      Become a contributor for community

                                                                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                                                      DigitalOcean Documentation

                                                                      Full documentation for every DigitalOcean product.

                                                                      Resources for startups and SMBs

                                                                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                                      Get our newsletter

                                                                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                                      New accounts only. By submitting your email you agree to our Privacy Policy

                                                                      The developer cloud

                                                                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                                      Get started for free

                                                                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                                      *This promotional offer applies to new accounts only.