Factory Design Pattern in Java with Examples | Beginner to Advanced Tutorial

Reading Time: 10–12 minutes

The Factory Design Pattern is one of the most commonly used creational design patterns in Java. It provides a way to create objects without exposing the object creation logic to the client. Instead of creating objects using the new keyword directly, object creation is delegated to a factory class.

This pattern improves code flexibility, reduces tight coupling, and makes applications easier to maintain and extend.

This tutorial explains the Factory pattern in a beginner-friendly way with simple examples, real-world understanding, implementation steps, and interview-level concepts.

What is Factory Design Pattern

The Factory pattern provides an interface or method to create objects while hiding the actual creation logic.

Instead of creating objects directly using the new keyword, we ask a factory to create the object.

Simple definition:

The Factory pattern encapsulates object creation logic and returns objects based on input or requirement.

Why Do We Need Factory Pattern

Let us understand the problem first.

Suppose we are building a payment application that supports multiple payment methods like UPI and Card.

Problem Without Factory Pattern


package com.codekatha;

class PaymentService {

    public void pay(String type) {

        if (type.equals("UPI")) {
            UpiPayment payment = new UpiPayment();
            payment.pay();
        }
        else if (type.equals("CARD")) {
            CardPayment payment = new CardPayment();
            payment.pay();
        }
    }
}

Problems in This Approach

Tight coupling between service and concrete classes
Large if-else conditions
Hard to add new payment types
Code modification required for every new feature
Difficult to maintain and test

We need a better approach where object creation is handled separately.

Solution – Factory Pattern

The Factory pattern moves object creation logic into a separate class called a factory.

The client simply asks the factory for an object and uses it. The client does not know how the object is created.

Key Idea Behind Factory Pattern

Separate object creation from object usage.
Hide creation logic from client.
Return objects based on input.

Step-by-Step Factory Pattern Implementation

Step 1 – Create a Common Interface

All objects created by the factory must follow a common interface.


package com.codekatha;

interface Payment {
    void pay();
}

Step 2 – Create Concrete Classes

Different implementations provide different behavior.


package com.codekatha;

class UpiPayment implements Payment {

    public void pay() {
        System.out.println("Payment done using UPI");
    }
}

class CardPayment implements Payment {

    public void pay() {
        System.out.println("Payment done using Card");
    }
}

Step 3 – Create Factory Class

The factory decides which object to create.


package com.codekatha;

class PaymentFactory {

    public static Payment getPayment(String type) {

        if (type.equals("UPI")) {
            return new UpiPayment();
        }
        else if (type.equals("CARD")) {
            return new CardPayment();
        }

        throw new IllegalArgumentException("Invalid payment type");
    }
}

Step 4 – Client Code

The client asks the factory for an object instead of creating it.


package com.codekatha;

class FactoryDemo {

    public static void main(String[] args) {

        Payment payment = PaymentFactory.getPayment("UPI");
        payment.pay();
    }
}

What We Achieved Using Factory

Object creation logic is centralized.
Client code is simple.
Loose coupling achieved.
Easy to extend system.

Real-Life Example of Factory Pattern

Think of a restaurant.

Customer orders food.
Kitchen prepares food.
Customer does not cook.

The kitchen acts as a factory that creates objects and gives them to the client.

Factory Pattern vs Using new Keyword

Without Factory


Payment payment = new UpiPayment();

Client depends directly on implementation.

With Factory


Payment payment = PaymentFactory.getPayment("UPI");

Client depends only on abstraction.

How Factory Supports Open Closed Principle

Factory allows adding new classes without modifying client code.

For example, adding NetBanking payment requires:

Create new class NetBankingPayment.
Update factory logic.
Client code remains unchanged.

Advantages of Factory Pattern

Encapsulates object creation logic
Reduces tight coupling
Improves maintainability
Supports scalability
Simplifies client code

Disadvantages of Factory Pattern

Adds extra classes
Factory may become complex if too many types
Requires understanding of abstraction

When Should You Use Factory Pattern

When object creation logic is complex
When object type depends on input
When multiple implementations exist
When loose coupling is required

Real-World Usage of Factory Pattern

Java Database DriverManager
Calendar.getInstance() method
Spring BeanFactory
Logging frameworks

Factory Pattern in Java Libraries

Java itself uses factory methods extensively.

Example


Calendar calendar = Calendar.getInstance();

The actual object creation is hidden from the user.

Common Interview Questions on Factory Pattern

What problem does Factory solve?
Difference between Factory and Abstract Factory?
Factory vs Builder pattern?
How does Factory reduce coupling?
Real-world use cases of Factory?

Simple Summary

Factory pattern hides object creation logic.
Client requests object from factory.
Factory decides which object to create.
Improves flexibility and maintainability.

Conclusion

The Factory Design Pattern helps create objects in a flexible and controlled way by separating object creation from object usage. It reduces dependency on concrete classes and improves scalability of applications.

Understanding Factory is important because many frameworks and enterprise applications rely heavily on this pattern for managing object creation.

Comments

Popular Posts on Code Katha

Java Interview Questions for 10 Years Experience

Sql Interview Questions for 10 Years Experience

Spring Boot Interview Questions for 10 Years Experience

Java interview questions - Must to know concepts

Visual Studio Code setup for Java and Spring with GitHub Copilot

Spring AI with Ollama

Data Structures & Algorithms Tutorial with Coding Interview Questions

Spring Data JPA

Topological Sort in Graph

Bit Manipulation and Bit Masking Concepts