In this tutorial, you’ll learn how to implement the Factory Design Pattern in Java — one of the most commonly used Creational Design Patterns that helps in creating objects without exposing the instantiation logic to the client.
The Factory Pattern is widely used in frameworks like Spring and Hibernate to manage object creation dynamically.
1. What Is the Factory Design Pattern?
The Factory Design Pattern provides an interface or method to create objects, allowing subclasses or logic inside the factory to decide which class to instantiate.
In simple words: Instead of calling new directly everywhere, you let a factory method handle object creation.
2. Real-World Example
Think of a Document Generator — it can create PDF, Word, or Excel documents.
You just tell the factory what type of document you need, and it returns the right object without you worrying about the underlying class.
3. Step-by-Step Implementation
Step 1: Create a Common Interface
Let’s create a common interface Document that will be implemented by all document types.
public interface Document {
void open();
}
Step 2: Create Multiple Implementations
Now, create concrete classes for different document types.
public class PdfDocument implements Document {
@Override
public void open() {
System.out.println("Opening PDF Document...");
}
}
public class WordDocument implements Document {
@Override
public void open() {
System.out.println("Opening Word Document...");
}
}
public class ExcelDocument implements Document {
@Override
public void open() {
System.out.println("Opening Excel Document...");
}
}
Step 3: Create the Factory Class
The factory class decides which type of object to create based on input.
public class DocumentFactory {
public static Document getDocument(String type) {
if (type == null) {
return null;
}
switch (type.toLowerCase()) {
case "pdf":
return new PdfDocument();
case "word":
return new WordDocument();
case "excel":
return new ExcelDocument();
default:
throw new IllegalArgumentException("Unknown document type: " + type);
}
}
}
Step 4: Use the Factory in Main Class
Now let’s test the pattern in action.
public class Main {
public static void main(String[] args) {
Document pdf = DocumentFactory.getDocument("pdf");
pdf.open();
Document word = DocumentFactory.getDocument("word");
word.open();
Document excel = DocumentFactory.getDocument("excel");
excel.open();
}
}
Output:
Opening PDF Document...
Opening Word Document...
Opening Excel Document...
5. Advantages of Factory Design Pattern
- Encapsulates object creation logic in one place.
- Promotes loose coupling between client and concrete classes.
- Makes adding new types easy (just create a new class and update the factory).
- Improves code readability and maintainability.
6. Real-World Use in Frameworks
- Spring Framework: Uses factories to create beans dynamically.
- JDBC: The
DriverManager.getConnection()method is a factory that returns a database connection object. - Logger Factory: Many logging frameworks like Log4j and SLF4J use factories to create log instances.
7. When to Use the Factory Pattern
- When object creation is complex or depends on input parameters.
- When you want to avoid exposing concrete class names in your code.
- When your code frequently needs to create different types of related objects.
8. When Not to Use
- If your application creates only one or two simple objects — a factory might add unnecessary complexity.
9. Conclusion
The Factory Design Pattern is one of the simplest yet most powerful creational design patterns in Java. It centralizes object creation and makes your application more scalable and maintainable.
Next time you find yourself writing multiple new statements for similar objects, consider using a Factory!
Next Step: Try combining the Factory Pattern with the Builder Pattern to handle complex object creation dynamically.
0 Comments