← Back to list

Factory Design Pattern vs Builder Design Pattern in Java

Complete Interview-Oriented Guide with Real-World Examples

Goyalnandini · 2026-06-07 13:51 · 3 claps · 4.1 min read
#factory-design-pattern #builder-design-pattern #java #creational-design-pattern
Open on Medium ↗

Factory Design Pattern vs Builder Design Pattern in Java

Complete Interview-Oriented Guide with Real-World Examples

Introduction

While learning Java and Spring Boot, one question often arises:

Why do we need Design Patterns when we can simply use the new keyword?

The answer is that as applications grow, object creation becomes complex. Design Patterns provide proven solutions to common software design problems.

Two of the most commonly used Creational Design Patterns are:

  1. Factory Design Pattern
  2. Builder Design Pattern

Both deal with object creation, but they solve different problems.

What Are Creational Design Patterns?

Creational Design Patterns focus on:

  • How objects are created
  • How object creation can be simplified
  • How to reduce coupling between classes
  • How to improve maintainability

Factory and Builder are part of the Creational Design Pattern family.

Factory Design Pattern

Definition

Factory Design Pattern provides a centralized way of creating objects without exposing the object creation logic to the client.

Instead of creating objects directly using:

new SomeClass();

the client asks a Factory to create the object.

Problem Before Factory Pattern

Consider a Payment System.

Payment payment = new CreditCardPayment();
payment.pay();

Later requirements change.

Now support:

  • Credit Card
  • UPI
  • Net Banking

The client code starts changing everywhere:

new UpiPayment();
new NetBankingPayment();

This creates tight coupling.

Factory Pattern Solution

Instead of:

new UpiPayment();

Use:

PaymentFactory.getPayment("UPI");

Now the client does not know which class is being instantiated.

The Factory handles it.

Factory Pattern Example

Step 1: Product Interface

interface Payment {
    void pay();
}

Step 2: Concrete Implementations

class CreditCardPayment implements Payment {
    @Override
    public void pay() {
        System.out.println("Paid using Credit Card");
    }
}
class UpiPayment implements Payment {
    @Override
    public void pay() {
        System.out.println("Paid using UPI");
    }
}
class NetBankingPayment implements Payment {
    @Override
    public void pay() {
        System.out.println("Paid using Net Banking");
    }
}

Step 3: Factory Class

class PaymentFactory {
    public static Payment getPayment(String type) {
        if(type.equalsIgnoreCase("UPI")) {
            return new UpiPayment();
        }
        if(type.equalsIgnoreCase("CARD")) {
            return new CreditCardPayment();
        }
        if(type.equalsIgnoreCase("NETBANKING")) {
            return new NetBankingPayment();
        }
        throw new IllegalArgumentException("Invalid Type");
    }
}

Step 4: Client

public class Main {
    public static void main(String[] args) {
        Payment payment =
                PaymentFactory.getPayment("UPI");
        payment.pay();
    }
}

Output:

Paid using UPI

Real-Life Analogy

Imagine a restaurant.

You do not go to the kitchen and create a burger yourself.

You ask the counter:

Customer
    ↓
Restaurant Counter
    ↓
Returns Burger

The counter acts like a Factory.

Factory Pattern in Automation Frameworks

One of the most common examples is DriverFactory.

Without Factory

if(browser.equals("chrome")) {
    driver = new ChromeDriver();
}
else if(browser.equals("firefox")) {
    driver = new FirefoxDriver();
}

With Factory

public class DriverFactory {
    public static WebDriver getDriver(String browser){
        switch(browser){
            case "chrome":
                return new ChromeDriver();
            case "firefox":
                return new FirefoxDriver();
            default:
                throw new RuntimeException();
        }
    }
}

Usage:

WebDriver driver =
        DriverFactory.getDriver("chrome");

Factory Pattern in Spring Boot

Spring internally uses Factory Pattern.

Examples:

ApplicationContext context;
context.getBean(EmployeeService.class);

The container decides:

  • Which bean to create
  • When to create
  • Whether to return existing bean

Internally this is Factory-based behavior.

Important Spring components:

  • BeanFactory
  • ApplicationContext

Interview Answer: Factory Pattern

Definition:

Factory Design Pattern is a Creational Design Pattern that centralizes object creation and hides instantiation logic from the client.

When to Use:

  • Multiple implementations exist
  • Object creation logic is complex
  • Loose coupling is required

Examples:

  • DriverFactory
  • BeanFactory
  • ApplicationContext
  • PaymentFactory

Builder Design Pattern

Now let us understand why Builder Pattern was invented.

Problem Before Builder Pattern

Consider:

class User {
    String firstName;
    String lastName;
    String email;
    String phone;
    String city;
    String country;
}

Constructor:

User(
    String firstName,
    String lastName,
    String email,
    String phone,
    String city,
    String country
)

Object creation:

User user = new User(
    "Nandini",
    "Goyal",
    "nandini@gmail.com",
    "9876543210",
    "Hyderabad",
    "India"
);

Looks manageable.

Now imagine:

  • 15 fields
  • 20 fields
  • 30 fields

Problems begin.

Problem 1: Constructor Telescoping

Developers start creating many constructors.

User(String name)
User(String name, String email)
User(String name, String email, String phone)
User(String name, String email, String phone, String city)

Number of constructors keeps growing.

This is called Constructor Telescoping.

Problem 2: Readability

new User(
    "Nandini",
    "Goyal",
    "9876543210",
    "Hyderabad"
);

Which value is phone?

Which value is city?

Hard to understand.

Problem 3: Optional Fields

Suppose only name and email are mandatory.

Without Builder:

new User(
    "Nandini",
    null,
    "nandini@gmail.com",
    null,
    null,
    null
);

Not clean.

Why Builder Pattern Was Invented

Builder Pattern was created to solve:

  • Constructor telescoping
  • Poor readability
  • Optional field handling
  • Complex object construction

Instead of creating the object in one step, it is created gradually.

Builder Pattern Example

Object Creation

User user =
        User.builder()
            .firstName("Nandini")
            .lastName("Goyal")
            .email("nandini@gmail.com")
            .city("Hyderabad")
            .build();

This is:

  • Readable
  • Flexible
  • Self-documenting

Real-Life Analogy

Imagine ordering a burger.

Factory Pattern:

Give me a burger.

Builder Pattern:

Burger
 + Cheese
 + Extra Patty
 + Mayo
 + Lettuce
 + Build

You configure the object step by step.

Builder Pattern in Automation Frameworks

Test Data Creation

Policy policy =
        Policy.builder()
              .policyType("Auto")
              .premium(5000)
              .build();

API Payload Creation

Request request =
        Request.builder()
               .name("Nandini")
               .role("Admin")
               .city("Hyderabad")
               .build();

Browser Configuration

BrowserConfig config =
        BrowserConfig.builder()
                .browser("chrome")
                .headless(true)
                .maximize(true)
                .build();

Builder Pattern in Spring Boot

Most common usage:

Lombok @Builder

@Builder
public class Employee {
    private String name;
    private String email;
}

Usage:

Employee employee =
        Employee.builder()
                .name("Nandini")
                .email("nandini@gmail.com")
                .build();

Important:

Many developers think:

@Builder

is the Builder Pattern.

Actually:

Lombok simply generates Builder Pattern code automatically.

The Design Pattern already existed.

Lombok only removes boilerplate code.

Famous Builder Pattern Examples in Java

StringBuilder

StringBuilder sb =
        new StringBuilder();
sb.append("Hello")
  .append(" ")
  .append("Nandini");

Java HttpClient

HttpRequest request =
        HttpRequest.newBuilder()
                .uri(uri)
                .header("Authorization", token)
                .GET()
                .build();

Classic Builder Pattern.

Interview Answer: Builder Pattern

Definition:

Builder Design Pattern is a Creational Design Pattern used to construct complex objects step by step, especially when objects contain many optional parameters.

Why Use It?

  • Avoid constructor telescoping
  • Improve readability
  • Handle optional fields
  • Build immutable objects
  • Create complex configurations

Common Uses:

  • DTOs
  • Request Objects
  • Response Objects
  • Test Data
  • Browser Configurations
  • Lombok @Builder

Factory vs Builder

The most important interview comparison.

Factory PatternBuilder PatternDecides WHAT object to createDecides HOW object is configuredCreates object in one stepCreates object step by stepHides creation logicHides construction complexityReturns object directlyBuilds object graduallyExample: DriverFactoryExample: UserBuilder

Easy Memory Trick

Factory Pattern:

WHAT should be created?

Builder Pattern:

HOW should it be created?

Example:

DriverFactory.getDriver("chrome");

Factory decides:

ChromeDriver or FirefoxDriver?

Builder:

User.builder()
    .name("Nandini")
    .email("abc@gmail.com")
    .build();

Builder decides:

How should User be configured?

Final Interview Summary

Factory Pattern:

  • Centralizes object creation
  • Hides instantiation logic
  • Promotes loose coupling
  • Used in DriverFactory, BeanFactory, ApplicationContext

Builder Pattern:

  • Solves constructor telescoping
  • Handles optional parameters
  • Improves readability
  • Commonly used with Lombok @Builder
  • Ideal for DTOs, Requests, Test Data, Configurations

The simplest way to remember:

Factory = What object should be created?

Builder = How should the object be constructed?


메타데이터
post_id
eb80e00a9aa5
slug
factory-design-pattern-vs-builder-design-pattern-in-java-eb80e00a9aa5
url
https://medium.com/@goyalnandini2001/factory-design-pattern-vs-builder-design-pattern-in-java-eb80e00a9aa5
canonical_url
https://medium.com/@goyalnandini2001/factory-design-pattern-vs-builder-design-pattern-in-java-eb80e00a9aa5
author_url
https://medium.com/@goyalnandini2001
status
ok
fetched_at
2026-06-23 17:05:31