Factory Design Pattern in Java
Overview
The factory design pattern is used in cases when there are multiple subclasses of a parent class or superclass. Using the input provided and the factory design pattern, we can return one of the subclasses of the superclass.
In a factory design pattern, we define an interface or abstract class and the subclasses decide which object to instantiate. The factory design pattern is also known as Factory Method Pattern or Virtual Constructor.
Introduction to Factory Design Pattern
Before learning about implementation, examples, advantages, and use cases of the factory design pattern let us first learn about inheritance, abstract classes, and interfaces.
Inheritance is one of the key concepts of Object Oriented Programming (OOP), which allows one class to acquire all the properties and behaviors of a superclass or parent class. As we know, Java does not support multiple inheritances i.e. a child class cannot acquire the properties and behaviors of more than one superclass. So, interfaces came into the picture.
An 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.
An interface contains a set of function definitions 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).
The factory design pattern is used in cases when there are multiple subclasses of a parent class or superclass. Using the input provided and the factory design pattern, we can return one of the subclasses of the superclass. In a factory design pattern, we define an interface or abstract class and the subclasses decide which object to instantiate. The factory design pattern is also known as Factory Method Pattern or Virtual Constructor.
The factory design pattern comes under the category of creational design pattern because the factory design pattern talks about the instantiation of an object. As the name suggests, in factory design patterns there are Factory methods that are involved in object creation. So, a factory design pattern is one of the best ways of creating objects where we want to abstract object creation logic from the client.
Now let us learn about the implementation, examples, advantages, and use cases of the factory design pattern or factory methods.
Implementation
Let us see the implementation of the factory design patterns.
- First we define a factory method inside an interface.
- The sub-class can now implement the defined factory method and decide which object to be created.
Note : Polymorphism is one of the key concepts of Object Oriented Programming, that allows us to perform a single action in many ways. Polymorphism simply means many forms.
As we know, the constructors are not polymorphic so we can use subclasses for object creation, in this way we are adding polymorphic behavior to instantiation (i.e. adding polymorphic behavior to constructors).
Since the factory design pattern in java is used to add polymorphic behavior to constructors of a class, the factory design pattern is also known as a virtual constructor.
Refer to the example sections below for code implementation.
Advantage of Factory Design Pattern
Some of the advantages of the factory design pattern in java :
- Using the factory design pattern, the subclasses can choose which type of objects to create.
- Using the factory design pattern, we can hide or abstract object creation logic from the client.
- The factory design pattern promotes loose-coupling i.e. eliminating the need to bind application-specific classes into the code.
- Using the factory design pattern, we can create an abstract class or interface that can work with any classes that implement or extends the factory method(s).
- It can also be used to return existing instances of subclasses multiple times.
Factory Design Pattern Super Class
A superclass in the factory design pattern can be an abstract class, a normal class, or an interface. The factory design pattern provides an interface for object creation as well as allows the subclasses to change the type of object that will be created.
To understand the concept of the superclass in factory design patterns, let us take a real-world problem example. Suppose we want to build a logistic management system. Initially, the first version of our application only supported transportation through trucks (defined under the Truck class). After some time, our company has expanded and now we need airplanes and ships for transportation to larger distances. So, adding the implementation of ships and another new mode of transport changes the entire codebase. This regular change of code implementation makes the code pretty nasty and hard to understand.
By using the factory methods, we can simplify our job. We can replace the direct object construction calls (calls to constructors using the new keyword) with the special calls to the factory method.
Refer to the image provided below to understand the scenario better.
So, by just using the factory method calls, we can return the type of object we want as we can see in the image above.
Factory Design Pattern Sub Classes
Subclasses are those classes that implement or extend the class built using the factory design pattern.
As we have seen in the example provided above a factory design pattern moved the constructor call from one part of the program to another. Now, we can override the factory method subclass and change the class of products being created by the method. The subclasses use the common class or interface to return different types of products.
Note : The return type of the factory method of the base class should be the same as declared in the interface.
Refer to the image provided below to understand the scenario better.
Factory Class
A factory class is used to construct instances of other classes. A factory method is a static method that returns an object of the class' type. A class containing a factory method is called a factory class. The factory methods are used to return an instance of a subclass.
A Real-World Example of Factory Method
We have learned a lot about the factory design pattern, let us now implement a real-life example for better understanding.
Suppose we are planning to make a program that will calculate the water bill payment. We will first create an abstract class called Plan(factory design pattern) and then the concrete classes() that extend the abstract classes. We will be creating a factory class named GetPlan.
Sub-class (GenerateBill) will use the factory class GetPlan to get objects. The GenerateBill class will pass information about the type of plan like Domestic/ Commercial/ Institutional to get desired objects.
Let us see the code step by step for better understanding.
1. Creating the abstract class Plan :
2. Creating concrete classes that will extend the Plan class :
a. Domestic plan class :
b. Commercial plan class :
c. Institutional plan class :
3. Creating factory class (GetPlan) for generating objects pf concrete class :
4. Finally, generating bills using the GetPlan class bases on the information passed :
Create a Notification Interface
Now, let us take one more example of the Notification interface. Suppose we want to implement the notification services like email, SMS, etc. through notification service.
The design of the Notification interface and its supporting concrete and Factory class is shown below :
We have three concrete classes implementing the Notification interface. We also have a concrete class named NotificationFactory which is used to get the Notification object as per the needs.
Let us see the code step by step for better understanding.
1. Creating the notification interface :
Refer to the section below for further steps.
Create All Implementation Classes
After creating the Notification interface, we will now be creating all the implementation classes :
Creating the three implementing classes :
-
SMS Notification :
-
Email Notification :
-
Push Notification :
Refer to the section below for further steps.
Create a Factory Class NotificationFactory.java to Instantiate Concrete Class
After creating all the implementation classes, we will now be creating the factory class for object instantiation :
Creating Factory class :
Refer to the section below for further steps.
Real-time Examples
Finally, creating objects using the factory class to see the output :
Output :
Conclusion
- The factory design pattern is used in cases when there are multiple subclasses of a parent class or superclass. Using the input provided and the factory design pattern, we can return one of the subclasses of the superclass.
- In a factory design pattern, we define an interface or abstract class and the subclasses decide which object to instantiate.
- The factory design pattern is also known as Factory Method Pattern or Virtual Constructor.
- Using the factory design pattern, the subclasses can choose which type of objects to create.
- Using the factory design pattern, we can hide or abstract object creation logic from the client.
- The factory design pattern promotes loose coupling which helps eliminate the need to bind application-specific classes into the code.
- Using the factory design pattern, we can create an abstract class or interface that can work with any classes that implement or extend the factory method(s).
- It can also be used to return existing instances of subclasses multiple times.
Embark on a design expedition with our Instagram System Design course, an immersive experience that accelerates your growth.