Factory Design Pattern in Java
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 aswitch. 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
| Component | Responsibility | In the examples below |
|---|---|---|
| Product | Interface every created object implements | ShippingMethod, OrderFormatter |
| Concrete Product | A real implementation of the product | ExpressShipping, CsvFormatter |
| Creator / Factory | Owns the method that returns a product | ShippingFactory, ExportJob |
| Concrete Creator | Factory Method only: subclass that overrides it | CsvExportJob |
| Client | Gets a product from the creator and uses it via the interface | main, 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.
createFormatter() and creates its own concrete product, while ExportJob only knows the OrderFormatter interface.- OrderFormatter is the product. Dashed lines with hollow triangles mean "implements": the two formatters are concrete products.
- ExportJob is the abstract creator (italics mark abstract elements). It uses the interface only.
- Solid lines with a hollow triangle mean "extends": the two jobs are concrete creators.
- 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):
- The client creates a
CsvExportJoband holds it as anExportJob. - It calls
export(orders), afinalmethod defined once in the base class. export()callscreateFormatter(); dynamic dispatch runs the subclass override.- The override returns
new CsvFormatter()as anOrderFormatter. export()callsheader(), thenrow()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()andNumberFormat.getCurrencyInstance(locale)return locale-specific subclasses. - Spring Framework: the IoC container is a
BeanFactory,@Beanmethods are factory methods, andFactoryBean<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:
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")));
}
}
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:
chargeandcollectdiffer, 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.
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
ShippingMethodis the product; the*Shippingclasses 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
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
valueOf()converts each string into an enum constant.create()returns a product typed asShippingMethod.- The 2.4 kg parcel is charged as 3 kg.
"DRONE"makesvalueOf()throw before the factory runs.
Practical Example: Order Export with the Factory Method
Problem: export orders in several formats without changing the export steps.
import java.math.BigDecimal;
import java.util.List;
import java.util.StringJoiner;
public class OrderExportDemo {
record Order(String id, String customer, BigDecimal total) { }
// Product
interface OrderFormatter {
String header();
String row(Order order);
}
// Concrete products
static final class CsvFormatter implements OrderFormatter {
public String header() { return "id,customer,total"; }
public String row(Order o) { return o.id() + "," + o.customer() + "," + o.total(); }
}
static final class MarkdownFormatter implements OrderFormatter {
public String header() { return "| id | customer | total |" + System.lineSeparator() + "|----|----------|-------|"; }
public String row(Order o) { return "| " + o.id() + " | " + o.customer() + " | " + o.total() + " |"; }
}
// Creator: the export steps are fixed, the formatter is left to subclasses
abstract static class ExportJob {
protected abstract OrderFormatter createFormatter(); // the factory method
public final String export(List<Order> orders) {
OrderFormatter formatter = createFormatter();
StringJoiner out = new StringJoiner(System.lineSeparator());
out.add(formatter.header());
orders.forEach(order -> out.add(formatter.row(order)));
return out.toString();
}
}
// Concrete creators
static final class CsvExportJob extends ExportJob {
@Override
protected OrderFormatter createFormatter() { return new CsvFormatter(); }
}
static final class MarkdownExportJob extends ExportJob {
@Override
protected OrderFormatter createFormatter() { return new MarkdownFormatter(); }
}
public static void main(String[] args) {
List<Order> orders = List.of(
new Order("A-101", "Meera", new BigDecimal("1250.00")),
new Order("A-102", "Kabir", new BigDecimal("349.50")));
List<ExportJob> jobs = List.of(new CsvExportJob(), new MarkdownExportJob());
for (ExportJob job : jobs) {
System.out.println("--- " + job.getClass().getSimpleName() + " ---");
System.out.println(job.export(orders));
}
}
}
Important classes and methods
ExportJobis the creator;createFormatter()is theprotectedfactory method.export()isfinal: subclasses change the format, not the steps.- Each concrete creator is the only class that names its formatter.
Expected output
--- CsvExportJob ---
id,customer,total
A-101,Meera,1250.00
A-102,Kabir,349.50
--- MarkdownExportJob ---
| id | customer | total |
|----|----------|-------|
| A-101 | Meera | 1250.00 |
| A-102 | Kabir | 349.50 |
How it runs
maincalls the inheritedexport()on each job.export()callscreateFormatter(); the subclass override picks the format.- The same loop writes the header and one row per order.
Adding JSON needs two new classes; ExportJob does not change.
Real-World Enterprise Example: Payment Gateway Registry
Problem: the section 7 checkout, rebuilt for frequent new payment methods and many request threads.
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;
public class PaymentGatewayFactoryDemo {
enum PaymentMethod { CARD, UPI, NET_BANKING, WALLET }
record PaymentRequest(String orderId, PaymentMethod method, BigDecimal amount) { }
record PaymentResult(String gateway, String status, BigDecimal fee) { }
// Product
interface PaymentGateway {
PaymentResult charge(PaymentRequest request);
}
// Concrete products
static final class CardGateway implements PaymentGateway {
public PaymentResult charge(PaymentRequest request) {
BigDecimal fee = request.amount().multiply(new BigDecimal("0.02")).setScale(2, RoundingMode.HALF_UP); // 2% card fee
return new PaymentResult("CardGateway", "APPROVED", fee);
}
}
static final class UpiGateway implements PaymentGateway {
public PaymentResult charge(PaymentRequest request) {
return new PaymentResult("UpiGateway", "APPROVED", new BigDecimal("0.00"));
}
}
static final class NetBankingGateway implements PaymentGateway {
public PaymentResult charge(PaymentRequest request) {
return new PaymentResult("NetBankingGateway", "PENDING_BANK_CONFIRMATION", new BigDecimal("15.00"));
}
}
// Factory: a registry filled at startup instead of a hard-coded switch
static final class PaymentGatewayFactory {
private final Map<PaymentMethod, Supplier<? extends PaymentGateway>> registry;
PaymentGatewayFactory(Map<PaymentMethod, Supplier<? extends PaymentGateway>> registry) {
this.registry = Map.copyOf(registry); // immutable copy: safe to share between threads
}
PaymentGateway forMethod(PaymentMethod method) {
Supplier<? extends PaymentGateway> supplier = registry.get(Objects.requireNonNull(method, "method"));
if (supplier == null) {
throw new UnsupportedOperationException("No gateway registered for " + method);
}
return supplier.get();
}
}
// Client: knows the factory and the interface, never a concrete gateway
static final class CheckoutService {
private final PaymentGatewayFactory gateways;
CheckoutService(PaymentGatewayFactory gateways) {
this.gateways = gateways;
}
String pay(PaymentRequest request) {
PaymentResult result = gateways.forMethod(request.method()).charge(request);
return "%s via %s: %s, fee Rs. %s".formatted(request.orderId(), result.gateway(), result.status(), result.fee());
}
}
public static void main(String[] args) {
Map<PaymentMethod, Supplier<? extends PaymentGateway>> gateways = new EnumMap<>(PaymentMethod.class);
gateways.put(PaymentMethod.CARD, CardGateway::new);
gateways.put(PaymentMethod.UPI, UpiGateway::new);
gateways.put(PaymentMethod.NET_BANKING, NetBankingGateway::new);
CheckoutService checkout = new CheckoutService(new PaymentGatewayFactory(gateways));
List<PaymentRequest> requests = List.of(
new PaymentRequest("ORD-1", PaymentMethod.CARD, new BigDecimal("2499.00")),
new PaymentRequest("ORD-2", PaymentMethod.UPI, new BigDecimal("640.00")),
new PaymentRequest("ORD-3", PaymentMethod.NET_BANKING, new BigDecimal("12000.00")),
new PaymentRequest("ORD-4", PaymentMethod.WALLET, new BigDecimal("99.00")));
for (PaymentRequest request : requests) {
try {
System.out.println(checkout.pay(request));
} catch (UnsupportedOperationException e) {
System.out.println(request.orderId() + " failed: " + e.getMessage());
}
}
}
}
Important classes and methods
- The factory holds a registry of
Suppliers instead of aswitch. Map.copyOf()makes the registry immutable, so threads read it without locks.forMethod()fails fast instead of returningnull.CheckoutServicegets the factory through its constructor, so tests can pass fakes.
Expected output
ORD-1 via CardGateway: APPROVED, fee Rs. 49.98
ORD-2 via UpiGateway: APPROVED, fee Rs. 0.00
ORD-3 via NetBankingGateway: PENDING_BANK_CONFIRMATION, fee Rs. 15.00
ORD-4 failed: No gateway registered for WALLET
How it runs
mainregisters three gateways, the job Spring would do at startup.pay()asks the factory for the gateway matching each request.- The card fee is 2% of 2499.00, which is 49.98.
WALLETis unregistered, so the factory throws and the client reports it.
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
nullhides 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 withcomputeIfAbsent, and share only thread-safe products.
Common mistakes
- Overengineering: a factory for one class. Plain
newis 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
| Aspect | Simple Factory | Factory Method | Abstract Factory | Builder |
|---|---|---|---|---|
| GoF pattern? | No, an idiom | Yes | Yes | Yes |
| How the type is chosen | A parameter, often an enum | A subclass overrides a method | One factory object per product family | Build steps, then build() |
| What it creates | One product | One product | A family of related products | One complex object |
| Main mechanism | switch or a registry | Inheritance | Composition | Step-by-step configuration |
| Java example | ShippingFactory above | Collection.iterator() | Light and dark UI kits | HttpRequest.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.