Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Factory Design Pattern?
3.
Implementation
3.1.
Factory Design Pattern Super Class
3.2.
Factory Design Pattern Sub Class
3.3.
Output
4.
Advantages of Factory Design Pattern
5.
Frequently Asked Questions
5.1.
What is the factory design pattern?
5.2.
What is the best example of factory design pattern?
5.3.
What is the purpose of factory method design pattern?
5.4.
What is the factory design pattern in MVC?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Factory Design Pattern in Java

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

The programmers use different design patterns to create software in a reliable, easy-to-understand, and efficient way. Today, we will learn about one of Java's most used design patterns, the factory design pattern.

Factory Design Pattern in Java

In this blog, we will study factory design patterns. We will also discuss some programming code for better understanding. Are you ready to 🧠 learn? Let's get started!

What is Factory Design Pattern?

A Factory design pattern or Factory method pattern is an example of a creational pattern. The creational patterns are used to create objects. The factory patterns are used when defining an interface or abstract class with multiple subclasses for an object. Based on the input, the factory design pattern returns one of these subclasses. It is useful when we need many objects of similar types, but we don't want to specify the type of object at the time of creation.

Before discussing the implementation of factory design patterns, first, we need to understand what are inheritance, abstract classes, and interfaces to have a clear picture of what factory design patterns are.

  • Inheritance: allows one class to obtain all the properties of a parent class. It is one of the critical concepts of Object Oriented Programming (OOP). Java does not support multiple inheritances in classes, i.e., a child class cannot acquire the properties and behaviors of more than one superclass. So, interfaces were introduced.
  • Interface: is the template of a class. Interfaces are similar to classes in Java, but the only difference is that a class can implement more than one interface in Java. It contains functions that a class can implement.
  • Abstract classes: are classes that may or may not include abstract methods. We cannot instantiate an abstract class (objects of abstract classes cannot be created).
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Implementation

Let us now learn the implementation of the factory design pattern.

Factory Design Pattern Super Class

In Factory Design pattern, a super class provides a skeleton for the subclasses to be created. It allows the subclass to extend itself and change the type of object to be returned. It acts as an interface for object creation. It can either be a normal class, an abstract class or an interface.

Suppose we want to create a program to calculate the movie ticket bill. Firstly, we will create an abstract class called Ticket (super class). 

import java.io.*;
abstract class Ticket {
	protected double Price;
	abstract void getPrice();

	public void calculateBill(int units) {
		System.out.println(units*Price);
  	}
}

Factory Design Pattern Sub Class

The class that extend or implement the super class in factory design pattern are known as sub class. These classes are the interface to return different types of object based on need. They override the super class's methods to have their own implementation

Now, we will create sub classes that extend the Ticket abstract class.

class  LowerSeat extends Ticket {
	public void getPrice() {
	Price = 225;
	}
}

class  MiddleSeat extends Ticket {
	public void getPrice() {
	Price = 275;
	}
}

class  BalconySeat extends Ticket {
	public void getPrice() {
	Price = 325;
	}
}

 

The above three classes: LowerSeat, MiddleSeat and BalconySeat are known as sub classes.

Create a GetTicketFactory to generate an object of concrete classes based on given information.

class GetTicketFactory
{
	public Ticket getTicket(String TicketType) {
	if(TicketType == null) {
		return null;
	}
   
	if(TicketType.equalsIgnoreCase("LowerSeat")) {
		return new LowerSeat();
	}
	else if(TicketType.equalsIgnoreCase("MiddleSeat")) {
		return new MiddleSeat();
	}
	else if(TicketType.equalsIgnoreCase("BalconySeat")) {
		return new BalconySeat();
	}
	return null;
	}
}

 

Lastly, we will generate the bill using GetTicketFactory to get the object of classes by passing information such as the type of tickets LowerSeat or MiddleSeat, or BalconySeat.

class GenerateBill {
	public static void main(String args[])throws IOException {
		GetTicketFactory TicketFactory = new GetTicketFactory();
   
	System.out.print("Enter the type of tickets for which the bill will be generated: ");
	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   
	String TicketType = br.readLine();
	System.out.print("Enter the number of tickets for bill will be calculated: ");
	int units = Integer.parseInt(br.readLine());
	Ticket p = TicketFactory.getTicket(TicketType);
	System.out.print("Bill amount for "+TicketType+" of  "+units+" tickets is: ");
	p.getPrice();
	p.calculateBill(units);
	}
}

Output

Code output -1

Code output-2

The first image shows the Bill amount for the first input as LowerSeat, and the number of tickets is 5, and the second input as BalconySeat, and the number of tickets is 4.

The second image shows an error as the MidSeat was not defined in the program. Instead, it was MiddleSeat.

In the code above, the client code doesn't need to know the details of object creation. The client only needs to know the interface of the Ticket class, GenerateBill, and GetTicketFactory class. The Factory pattern abstracts the object creation process, making it easy to change the type of object created without affecting the client code.

Advantages of Factory Design Pattern

Now, let's talk about the advantages of factory design patterns in Java:

  • The client code only needs to know the interface of the factory class, and it doesn't need to know how the object was created. So it decouples the client from the creation process.
     
  • We can change the object creation process by changing the factory class and not disturbing the client code. This makes the code more maintainable.
     
  • As the client only knows the interface of the factory class instead of the creation process, this makes the code more readable. 

Frequently Asked Questions

What is the factory design pattern?

The factory design patterns are creational patterns used to create objects. We define an abstract class with multiple subclasses. It provides an interface for creating objects without specifying the exact class of object that will be created.

What is the best example of factory design pattern?

The best example for understanding Factory Design Pattern is the above example in this blog which used an abstract class called Ticket and 3 sub-classes for each type of ticket possible. Then we created a factory class GetTicketFactory which returned the appropriate object depending on the type of ticket to be booked.

What is the purpose of factory method design pattern?

Factory method design pattern allows the subclasses to override the super class's methods and return the appropriate object type. It does not put the responsibility on the application to create the correct object type, it instead puts the responsibility on the Factory Class to create the appropriate object type and return to the application.

What is the factory design pattern in MVC?

Factory design pattern in MVC is used to create objects of a super class by taking away the responsibility from the application and giving it to the Factory Class to determine which object type is appropriate for each request.

Conclusion

We expect this article was insightful and that you learned something new today. In this blog, we learned about factory design patterns in Java. It is used in the case where there are multiple subclasses of a parent class. Depending on the input, we return one of these subclasses. We also discussed its implementation, advantages, and some examples in Java for clarity.
If you want to learn more about design patterns, do visit.

 

You may refer to our Guided Path on Code Studios for enhancing your skill set on DSACompetitive ProgrammingSystem Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy Learning, Ninja!

Previous article
Decorator Design Pattern
Next article
Upcasting and Downcasting in Java
Live masterclass