00:00

Factory Design Pattern in Java

Last updated:

The factory design pattern in Java is a creational pattern that moves object creation into a dedicated method or class. The client asks for what it needs, such as "express shipping", and works with an interface, while the factory decides which concrete class to build.

It matters because every new CardGateway() ties a service to one class, and as implementations grow, the same if-else chain spreads across the code. A factory gives that decision one home. It is one of the creational design patterns.

1. What Is the Factory Design Pattern?

The core idea: separate the code that decides which object to create from the code that uses it. The caller depends on an abstraction; one place knows the concrete classes. The name covers two related designs:

  • Simple Factory: a class with a method such as create(type) that returns the right implementation, usually through a switch. It is a common idiom, not one of the 23 Gang of Four (GoF) patterns.
  • Factory Method: the GoF pattern. A base class declares a method that returns a product, and each subclass overrides it. The GoF intent is: "Define an interface for creating an object, but let subclasses decide which class to instantiate."

Both apply the rule "program to an interface, not an implementation". This tutorial covers both.

2. Key Components

ComponentResponsibilityIn the examples below
ProductInterface every created object implementsShippingMethod, OrderFormatter
Concrete ProductA real implementation of the productExpressShipping, CsvFormatter
Creator / FactoryOwns the method that returns a productShippingFactory, ExportJob
Concrete CreatorFactory Method only: subclass that overrides itCsvExportJob
ClientGets a product from the creator and uses it via the interfacemain, CheckoutService

The client calls the creator, the creator instantiates a concrete product, and the client receives it as the product interface, never naming the concrete class.

3. When Is a Factory Useful?

  • The type is known only at runtime. A checkout form sends "EXPRESS", which must become a shipping object.
  • Creation needs more than new. A payment gateway needs a merchant key, timeout and retry policy, set up in one place.
  • A fixed process needs a varying part. An export job always writes a header and rows, but each subclass supplies the file format.

4. UML Class Diagram

The diagram shows the Factory Method version from the Practical Example tab.

Factory Method UML class diagram The abstract ExportJob declares createFormatter and uses the OrderFormatter interface. CsvExportJob and MarkdownExportJob extend ExportJob and create CsvFormatter and MarkdownFormatter, which implement OrderFormatter. «abstract» ExportJob + export(orders): String # createFormatter(): OrderFormatter «interface» OrderFormatter + header(): String + row(order): String uses extends implements CsvExportJob # createFormatter() MarkdownExportJob # createFormatter() MarkdownFormatter + header(), row() CsvFormatter + header(), row() «create» «create»
Factory Method: each concrete creator overrides createFormatter() and creates its own concrete product, while ExportJob only knows the OrderFormatter interface.
  1. OrderFormatter is the product. Dashed lines with hollow triangles mean "implements": the two formatters are concrete products.
  2. ExportJob is the abstract creator (italics mark abstract elements). It uses the interface only.
  3. Solid lines with a hollow triangle mean "extends": the two jobs are concrete creators.
  4. The «create» arrows are the only places concrete products are instantiated.

5. Step-by-Step Execution Flow

Here is what happens when the client calls new CsvExportJob().export(orders):

  1. The client creates a CsvExportJob and holds it as an ExportJob.
  2. It calls export(orders), a final method defined once in the base class.
  3. export() calls createFormatter(); dynamic dispatch runs the subclass override.
  4. The override returns new CsvFormatter() as an OrderFormatter.
  5. export() calls header(), then row() per order, and returns the text.

A Simple Factory is shorter: ShippingFactory.create(EXPRESS) runs a switch and returns a ShippingMethod.

6. Real-World Use Cases

  • E-commerce: pick a shipping, tax or discount calculator per country or customer choice.
  • Payments and banking: map card, UPI and net banking to gateway clients, or account types to statement generators.
  • Notifications: build an email, SMS or push sender from the user's preferred channel.
  • The JDK: Collection.iterator() is a classic Factory Method: each collection returns its own iterator class. Calendar.getInstance() and NumberFormat.getCurrencyInstance(locale) return locale-specific subclasses.
  • Spring Framework: the IoC container is a BeanFactory, @Bean methods are factory methods, and FactoryBean<T> plugs custom creation logic into the container.
  • Spring Boot services: an injected Map<String, PaymentGateway> holds every gateway bean by name, a ready-made registry.

7. Problem Without the Pattern

A checkout method that creates its own gateways:

CheckoutWithoutFactory.java
import java.math.BigDecimal;

public class CheckoutWithoutFactory {

    static final class CardGateway {
        String charge(BigDecimal amount) { return "Card charged Rs. " + amount; }
    }

    static final class UpiGateway {
        String collect(BigDecimal amount) { return "UPI collected Rs. " + amount; }
    }

    // Business logic and object creation are mixed in one method
    static String checkout(String method, BigDecimal amount) {
        if ("CARD".equals(method)) {
            return new CardGateway().charge(amount);
        } else if ("UPI".equals(method)) {
            return new UpiGateway().collect(amount);
        }
        throw new IllegalArgumentException("Unsupported payment method: " + method);
    }

    public static void main(String[] args) {
        System.out.println(checkout("CARD", new BigDecimal("499.00")));
        System.out.println(checkout("UPI", new BigDecimal("120.00")));
    }
}
Console
Card charged Rs. 499.00
UPI collected Rs. 120.00

It works, but:

  • Tight coupling: checkout() depends on every gateway class.
  • Duplication: refunds and reports copy the same if-else.
  • Poor maintainability: adding net banking means editing checkout logic.
  • Hard to test: a fake gateway cannot be swapped in.
  • No common type: charge and collect differ, so callers must know each class.

8. Solution Using the Pattern

Give all gateways one PaymentGateway interface, move the choice into a PaymentGatewayFactory, and let CheckoutService call charge() on whatever the factory returns.

Each problem above is solved: the service depends on one interface, the choice lives in one place, a new gateway is one class plus one registration line, and tests can supply a fake. The Enterprise Example tab builds this design.

9. Factory Design Pattern in Java: Code Examples

Each example is a single file that runs on Java 21 with java FileName.java.

Basic Example: Shipping Options with a Simple Factory

Problem: turn the shipping option chosen at checkout into an object that prices the parcel.

ShippingFactoryDemo.java
public class ShippingFactoryDemo {

    // Product: what every shipping option can do
    interface ShippingMethod {
        String name();
        int cost(double weightKg);
        String delivery();
    }

    // Concrete products
    static final class StandardShipping implements ShippingMethod {
        public String name() { return "Standard"; }
        public int cost(double weightKg) { return 40 + 10 * (int) Math.ceil(weightKg); }
        public String delivery() { return "in 5 days"; }
    }

    static final class ExpressShipping implements ShippingMethod {
        public String name() { return "Express"; }
        public int cost(double weightKg) { return 90 + 25 * (int) Math.ceil(weightKg); }
        public String delivery() { return "in 2 days"; }
    }

    static final class SameDayShipping implements ShippingMethod {
        public String name() { return "Same-day"; }
        public int cost(double weightKg) { return 150 + 40 * (int) Math.ceil(weightKg); }
        public String delivery() { return "today"; }
    }

    enum ShippingType { STANDARD, EXPRESS, SAME_DAY }

    // Factory: the only place that knows the concrete classes
    static final class ShippingFactory {
        private ShippingFactory() { }

        static ShippingMethod create(ShippingType type) {
            return switch (type) {          // no default: a new enum constant is a compile error here
                case STANDARD -> new StandardShipping();
                case EXPRESS -> new ExpressShipping();
                case SAME_DAY -> new SameDayShipping();
            };
        }
    }

    public static void main(String[] args) {
        double parcelKg = 2.4;
        String[] selections = {"STANDARD", "EXPRESS", "SAME_DAY", "DRONE"};   // e.g. values from a checkout form

        for (String selection : selections) {
            try {
                ShippingMethod method = ShippingFactory.create(ShippingType.valueOf(selection));
                System.out.printf("%-9s Rs. %d, delivered %s%n", method.name(), method.cost(parcelKg), method.delivery());
            } catch (IllegalArgumentException e) {
                System.out.println("Rejected: " + e.getMessage());
            }
        }
    }
}

Important classes and methods

  • ShippingMethod is the product; the *Shipping classes are concrete products.
  • ShippingFactory.create() is the factory, in a class with a private constructor.
  • The switch has no default, so a new enum constant fails compilation until it is mapped.

Expected output

Console
Standard  Rs. 70, delivered in 5 days
Express   Rs. 165, delivered in 2 days
Same-day  Rs. 270, delivered today
Rejected: No enum constant ShippingFactoryDemo.ShippingType.DRONE

How it runs

  1. valueOf() converts each string into an enum constant.
  2. create() returns a product typed as ShippingMethod.
  3. The 2.4 kg parcel is charged as 3 kg.
  4. "DRONE" makes valueOf() throw before the factory runs.

10. Best Practices and Common Mistakes

Best practices

  • Return the interface type from the factory, never the concrete class.
  • Prefer an enum and a switch expression over raw strings.
  • Fail fast on unknown input; returning null hides the bug.
  • Inject the factory through the constructor so tests can replace it.
  • Thread safety: stateless factories are safe. Keep registries immutable after startup, or use ConcurrentHashMap; cache with computeIfAbsent, and share only thread-safe products.

Common mistakes

  • Overengineering: a factory for one class. Plain new is clearer.
  • Leaking the concrete type, such as casting to CardGateway.
  • A "god factory" creating unrelated objects.
  • Business logic in the factory: it should build objects, not apply discounts.

11. When to Use and When Not to Use

Use a factory when implementations will grow, when creation needs hidden configuration, or when implementations must be swapped by configuration or in tests.

Skip it for records and DTOs, for a single implementation, or when a dependency injection container already wires the right bean. In small scripts the extra types cost more than they save.

12. Advantages and Disadvantages

Advantages

  • Loose coupling: clients depend on interfaces only.
  • One place for creation logic (Single Responsibility).
  • Easier extension without touching clients (Open/Closed).
  • Testability: fakes can be supplied through the factory.
  • Freedom to cache instances.

Disadvantages

  • More types and one more level of indirection to read.
  • Factory Method needs a subclass per product, which can multiply classes.
  • A switch-based factory still needs editing for new products.

13. Comparison with Similar Patterns

AspectSimple FactoryFactory MethodAbstract FactoryBuilder
GoF pattern?No, an idiomYesYesYes
How the type is chosenA parameter, often an enumA subclass overrides a methodOne factory object per product familyBuild steps, then build()
What it createsOne productOne productA family of related productsOne complex object
Main mechanismswitch or a registryInheritanceCompositionStep-by-step configuration
Java exampleShippingFactory aboveCollection.iterator()Light and dark UI kitsHttpRequest.newBuilder()

Choose a Simple Factory when one parameter decides the type, the Factory Method when subclasses supply one part of a fixed process, an Abstract Factory when several products must match, and a Builder when one type has many optional settings. They combine well: a factory can return a Singleton.

14. Summary

  • The factory design pattern in Java hides object creation behind a method; clients use interfaces.
  • Purpose: remove new-based coupling and centralise creation.
  • Components: Product, Concrete Product, Creator, Concrete Creator, Client.
  • A Simple Factory chooses by parameter; the GoF Factory Method lets subclasses decide.
  • Used for payment gateways, shipping, notifications, exporters, JDK iterators and Spring's BeanFactory.
  • Benefits: loose coupling, easier extension, easier testing.
  • Fail fast, keep registries immutable, and skip the factory when one class will do.

15. Java Design Pattern Interview Questions and Answers

Q1. Is a static factory method like List.of() the same as the Factory Method pattern?

No. A static factory method, as described in Effective Java, is a static method that replaces a constructor, for example List.of() or Integer.valueOf(). The GoF Factory Method is an instance method that subclasses override. Both hide the concrete class, but only the GoF version uses inheritance to vary the product.

Q2. Factory Method and Template Method often appear together. How are they different?

Template Method fixes the steps of an algorithm and lets subclasses fill in some steps. Factory Method is a step whose only job is to create an object. In the order export example, export() is a template method and createFormatter() is a factory method called from it. See the Template Method pattern for more.

Q3. Must a factory return a new object every time?

No. A factory controls creation, so it may return cached instances. Boolean.valueOf() always returns Boolean.TRUE or Boolean.FALSE, and Integer.valueOf() caches values from -128 to 127 by default. Sharing is safe only for immutable or stateless products. Stateful products must be created fresh for each caller.

Q4. How can a new implementation be added without editing the factory at all?

Let the implementations register themselves. In plain Java, java.util.ServiceLoader discovers implementations listed in META-INF/services or in provides clauses of module-info.java. In Spring Boot, each implementation is a bean, and the factory receives them all:

@Component
class PaymentGatewayFactory {
    private final Map<String, PaymentGateway> gateways;   // bean name -> bean

    PaymentGatewayFactory(Map<String, PaymentGateway> gateways) {
        this.gateways = Map.copyOf(gateways);
    }
}

Adding a gateway is then one new @Component class.

Q5. A reviewer says your switch-based factory violates the Open/Closed Principle. How do you respond?

They are partly right: adding a product means editing the switch. But the change is limited to one small method instead of being spread across every client, and a switch expression over an enum makes the compiler report every missing case. For a small, stable set of types that is a good trade-off. When types are added often or by other teams, move to a registry or ServiceLoader.