Hey, Tea Lovers! Let me continue our design pattern series by adding this post. The Factory Design Pattern or Factory Method Design Pattern. It is one of the widely used and easy-to-understand Design patterns. It’s an effortless yet effective way of hiding object creation complexity. That’s why it is under the creation pattern category. So let’s jump right into it.
I would be happy to connect with you guys on social media. It’s @coderstea on Twitter, Linkedin, Facebook, Instagram, and YouTube.
Please Subscribe to the newsletter to know about the latest posts from CodersTea.
Prerequisite to knowing Factory Design Pattern
Before understanding what a factory design pattern is, you need to understand what superclass and subclass are. I am pretty sure you are aware of this detail, if not, the following section describes it in brief. if you already know it, you can skip to this part
SuperClass VS SubClass / Parent VS Child Classes
A superclass is a class or interface that is defined as a base class. And subclasses are the one that extends or implements it (superclass). For example, Student is an interface (or you can make it a class, it is up to you). Now there can be multiple types of students. No, I am not talking about A+ or F students, I don’t want to make fun of myself here.
Instead, let’s say it’s based on different courses. Such as FinanceStudent
, ComputerStudent
or an ArtStudent
. These are different classes, but all these are of type students, right? So we will implement the Student
interface for each student type. As soon as you implement or extend any class, the current class becomes its subclass of it. In our case, All these students, FinanceStudent
, ComputerStudent
and ArtStudent
are subclasses of Student
. And Student
is the superclass or base class (yes, even though it’s an interface) of these subclasses.
interface Student {
String getName();
}
class FinanceStudent implements Student {
public String getName(){
// do something
}
}
// same for ComputerStudent and ArtStudent
Code language: PHP (php)
The Challenge
In our little example above, we have many student classes, and many more to come. Usually, we will create each student separately like the following.
Student st = new FinanceStudent("Student 1");
Student st2 = new ArtStudent("Stuent 2");
...
Student stN = new NthCoursedStudent("Student Nth");
Code language: JavaScript (javascript)
In the above example, every time you needed any student, you needed to explicitly select the appropriate student type and call the new keyword. Now the problem here is that let’s say for the Art Student we want to pass some default value every time we create the object. Or do we want to validate the provided string to the Student class? This will be very difficult to handle as the object creation is scattered throughout the code. And it will be more tedious because, for each student type, you need to add the validation logic. So how would we solve this challenge?
You must be thinking, What if we can collect all these student creation logic into a single class or function? Interesting point and what you are thinking is called the Factory Design Pattern. Let’s deep dive into it.
What is Factory Design Pattern
Simply put, It is a way of putting the object creation logic (similar type) into a single class or function. Similar to a factory. You just ask the factory to build a certain product. The factory takes care of the product building based on your requirement and gives you the final product. You don’t have to worry about what’s happening inside the factory.
In our previous example, we created the Student classes Nth time. Let us apply the Factory Design Pattern (in a very simple way) to it.
Creating a Factory Design Class
Keep in mind, that I am creating a very simple one, you may make it more tailored to your need.
Let us start with the Factory Base Class. And inside that create a function called createStudent
. And make it public
and static
for easy access. We will worry about how to create it later. Your code now may look like the following.
class StudentFactory {
public static Student createStudent(){
// TODO
return null;
}
}
Code language: PHP (php)
Now, how to determine which type of Student it needs to create? For that, we can use a String or can use an enum for more maintainable code.
enum StudentTypes {
FINANCE, ART, COMPUTER;
}
The next step is to get this enum as a parameter along with the Student name in the createStudent method. After that, we will simply do an if-else or switch condition. And if you are using the latest java, you can use this: Java Switch Statement is now more Powerful | Java 18. You createStudent
will now look like this.
public static Student createStudent(StudentTypes studentType,
String name) {
System.out.printf("Creating %s student object with name %s \n"
, studentType, name);
switch (studentType) {
case FINANCE:
return new FinanceStudent(name);
case ART:
return new ArtStudent(name);
case COMPUTER:
return new ComputerStudent(name);
default:
// returning null is not recommended
return new ComputerStudent(name);
}
}
Code language: JavaScript (javascript)
And that’s it, this is your factory design pattern. now you simply have to call the createStudent
function with the appropriate type enum and voila, you will get that student object. Now you must be wondering what the advantages of it are, right? Let’s take one of the scenarios I mentioned in the challenge section.
Benefits of Factory Design Pattern
Let us say we want to validate the provided name. Check if it is null or not. If null throw an exception. Before FDP, we would have to check the name independently before each creation logic. which would have been a redundant task. But now with the FDP function we created, we have to write and call the logic only once. We can write a null check just before the switch statement. Or in case you have a long logic for validation, just create a separate function and call it before the switch statement, easy.
if(name == null){
throw new RuntimeException("name is null");
}
Code language: JavaScript (javascript)
Example of Factory Design Pattern
There are many examples of this pattern. Many could be found in the java library itself. For a custom practical example, you can look at my hack on multiple database pooling. The post is about How to create a Multi-Database Pool in HikariCP.
Conclusion
That’s it for this post. Hope you have understood the basics of the Factory Design Pattern. It’s a very easy and simple design pattern out there. Please check out the How to create a Multi-Database Pool in HikariCP post for a practical example of this pattern. You can see the full code on GitHub.
See you in the next post. HAKUNA MATATA!!!
I would be happy to connect with you guys on social media. It’s @coderstea on Twitter, Linkedin, Facebook, Instagram, and YouTube.
Please Subscribe to the newsletter to know about the latest posts from CodersTea.