Skip to lesson

Simple factories and Factory Method

Checkout, renewals and refunds each pick a payment class with their own if and new. Adding wallet payments means finding every copy, and missing one breaks that screen.

The problem: new scattered through the code

A factory is code whose job is to create objects for other code, so callers ask for a type instead of naming a concrete class with new.

ShopLite's code grew messy: checkout, renewals and refunds each choose a payment class themselves. Here is the same choice copied three times.

Java
class Checkout {    PaymentMethod method = type.equals("UPI") ? new UpiPayment() : new CardPayment();}class Renewals {    PaymentMethod method = type.equals("UPI") ? new UpiPayment() : new CardPayment();}class Refunds {    PaymentMethod method = type.equals("UPI") ? new UpiPayment() : new CardPayment();}// a new WalletPayment means three edits, and three chances to forget one

The choice of concrete class is copied into every place, so each copy depends on every payment class. Miss one when adding a type and that screen silently falls back to card. The cure is to decide "which class for which type" in exactly one place.

Simple factory: PaymentFactory.create(type)

A simple factory is a class with one method that takes a key, such as "UPI", and returns the matching object through an interface type. The switch lives there and nowhere else.

A simple factory turns a key, such as "UPI", into the right object. In the program below, Checkout calls it and names no payment class.

Example 1 · A simple PaymentFactory

SimpleFactoryDemo.javaJava
import java.util.Locale;
interface PaymentMethod {    String name();    String pay(double amount);}
class CardPayment implements PaymentMethod {    public String name() { return "Card"; }    public String pay(double amount) { return String.format("charged Rs %.2f to card", amount); }}
class UpiPayment implements PaymentMethod {    public String name() { return "UPI"; }    public String pay(double amount) { return String.format("sent a UPI collect request for Rs %.2f", amount); }}
class CodPayment implements PaymentMethod {    public String name() { return "COD"; }    public String pay(double amount) { return String.format("will collect Rs %.2f in cash", amount); }}
class PaymentFactory {    static PaymentMethod create(String type) {        return switch (type.toUpperCase(Locale.ROOT)) {            case "CARD" -> new CardPayment();            case "UPI" -> new UpiPayment();            case "COD" -> new CodPayment();            default -> throw new IllegalArgumentException("Unknown payment type: " + type);        };    }}
class Checkout {    void pay(String orderId, double amount, String chosenType) {        PaymentMethod method = PaymentFactory.create(chosenType);   // no concrete class named here        System.out.println(orderId + " [" + method.name() + "] " + method.pay(amount));    }}
public class SimpleFactoryDemo {    public static void main(String[] args) {        Checkout checkout = new Checkout();        checkout.pay("ORD-101", 1499, "card");        checkout.pay("ORD-102", 349, "UPI");        checkout.pay("ORD-103", 650, "cod");        try {            checkout.pay("ORD-104", 99, "bitcoin");        } catch (IllegalArgumentException e) {            System.out.println("ORD-104 rejected: " + e.getMessage());        }    }}
Output
ORD-101 [Card] charged Rs 1499.00 to card
ORD-102 [UPI] sent a UPI collect request for Rs 349.00
ORD-103 [COD] will collect Rs 650.00 in cash
ORD-104 rejected: Unknown payment type: bitcoin

What this code does

  • Checkout names no concrete payment class; the factory is the only place that knows new CardPayment() and friends.
  • toUpperCase(Locale.ROOT) makes card, Card and CARD all work on every computer, and an unknown type throws instead of guessing.

Callers depend only on PaymentMethod and PaymentFactory. A simple factory is not one of the 23 GoF patterns, but it is the most common factory in real code.

Common mistake: a default branch that quietly returns card. Unknown keys should fail fast with a clear exception, as bitcoin does here.

Find the bug

Find the factory bug

Each snippet has one wrong line. Tap it, then check the fix.

Unknown types must be rejected, not paid by card.

Round 1 of 3

Static factory methods: List.of, Optional.of

A static factory method is a named static method that returns an instance of its class, used instead of a public constructor, such as List.of(...) or Money.ofRupees(...).

A static method that returns an instance can replace a public constructor. Money below has two named methods, and the JDK's List.of and Optional.of work the same way.

Example 2 · Static factory methods in the JDK and in your own class

StaticFactoryDemo.javaJava
import java.time.LocalDate;import java.util.List;import java.util.Optional;
final class Money {    private static final Money ZERO = new Money(0);    private final long paise;
    private Money(long paise) {                        // callers use the named methods        this.paise = paise;    }
    static Money ofRupees(long rupees) { return new Money(rupees * 100); }    static Money ofPaise(long paise) { return new Money(paise); }    static Money zero() { return ZERO; }               // may return a cached object
    Money plus(Money other) { return new Money(paise + other.paise); }
    @Override    public String toString() {        return String.format("Rs %d.%02d", paise / 100, paise % 100);    }}
public class StaticFactoryDemo {    public static void main(String[] args) {        List<String> sizes = List.of("S", "M", "L");        Optional<String> coupon = Optional.of("FEST100");        LocalDate saleDay = LocalDate.of(2026, 10, 20);        System.out.println(sizes + " " + coupon.get() + " " + saleDay);
        Money price = Money.ofRupees(1499);        Money fee = Money.ofPaise(4050);        System.out.println(price + " + " + fee + " = " + price.plus(fee));        System.out.println("zero() reuses one object? " + (Money.zero() == Money.zero()));
        try {            sizes.add("XL");        } catch (UnsupportedOperationException e) {            System.out.println("List.of gave an unmodifiable list");        }    }}
Output
[S, M, L] FEST100 2026-10-20
Rs 1499.00 + Rs 40.50 = Rs 1539.50
zero() reuses one object? true
List.of gave an unmodifiable list

What this code does

  • Money.ofRupees(1499) and Money.ofPaise(4050) both take a long; two constructors could not tell them apart, but two named methods can.
  • zero() returns the same cached object every time, and List.of returned a class you never named, which refuses add.

Static factory methods have three advantages over constructors. They have names: ofRupees and ofPaise take the same type but mean different things. They can return a cached object instead of a new one. And they can return a subtype or hidden class, which is how List.of gives an unmodifiable list without you naming its class.

Predict the output

Cached or new?

Read the code and pick the exact output.

Compare the objects the two methods return.

class Money {
private static final Money ZERO = new Money();
private Money() { }
static Money zero() { return ZERO; }
static Money of() { return new Money(); }
}
// in main:
System.out.println(Money.zero() == Money.zero());
System.out.println(Money.of() == Money.of());
Common names: of, from, valueOf, getInstance, newInstance, create.

Factory Method: subclasses decide what to create

Factory Method is a GoF pattern where a parent class calls an abstract creation method and each subclass decides which product class to create.

In Factory Method, the parent class holds the steps that stay the same and calls an abstract createPayment(). Each subclass below returns its own payment.

Example 3 · Factory Method: each checkout creates its own payment

FactoryMethodDemo.javaJava
interface PaymentMethod {    String name();    String pay(double amount);}
class CardPayment implements PaymentMethod {    public String name() { return "Card"; }    public String pay(double amount) { return String.format("charged Rs %.2f to card", amount); }}
class UpiPayment implements PaymentMethod {    private final String upiId;
    UpiPayment(String upiId) { this.upiId = upiId; }
    public String name() { return "UPI"; }    public String pay(double amount) { return String.format("collect request of Rs %.2f sent to %s", amount, upiId); }}
abstract class CheckoutFlow {    // The factory method: each subclass decides which PaymentMethod to create    protected abstract PaymentMethod createPayment();
    final void complete(String orderId, double amount) {        PaymentMethod method = createPayment();        System.out.println(orderId + " via " + method.name() + ": " + method.pay(amount));        System.out.println("  receipt emailed for " + orderId);    }}
class CardCheckout extends CheckoutFlow {    protected PaymentMethod createPayment() {        return new CardPayment();    }}
class UpiCheckout extends CheckoutFlow {    private final String upiId;
    UpiCheckout(String upiId) { this.upiId = upiId; }
    protected PaymentMethod createPayment() {        return new UpiPayment(upiId);    }}
public class FactoryMethodDemo {    public static void main(String[] args) {        CheckoutFlow card = new CardCheckout();        CheckoutFlow upi = new UpiCheckout("asha@okaxis");        card.complete("ORD-201", 2499);        upi.complete("ORD-202", 799);    }}
Output
ORD-201 via Card: charged Rs 2499.00 to card
  receipt emailed for ORD-201
ORD-202 via UPI: collect request of Rs 799.00 sent to asha@okaxis
  receipt emailed for ORD-202

What this code does

  • complete is written once in CheckoutFlow and is final; only createPayment() differs between subclasses.
  • UpiCheckout passes its own data (the UPI id) into the product it creates, which a single switch would have to receive as extra parameters.

Example 4 · Factory Method in the JDK: iterator()

IteratorFactoryMethodDemo.javaJava
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;import java.util.List;import java.util.TreeSet;
public class IteratorFactoryMethodDemo {    public static void main(String[] args) {        List<Collection<String>> carts = List.of(                new ArrayList<>(List.of("Pen", "Bag")),                new TreeSet<>(List.of("Cap", "Bottle")),                new ArrayDeque<>(List.of("Lamp")));
        for (Collection<String> cart : carts) {            Iterator<String> it = cart.iterator();     // each collection creates its own iterator class            StringBuilder items = new StringBuilder();            while (it.hasNext()) {                items.append(it.next()).append(' ');            }            System.out.println(cart.getClass().getSimpleName() + " -> " + it.getClass().getSimpleName()                    + ": " + items.toString().trim());        }    }}
Sample output
ArrayList -> Itr: Pen Bag
TreeSet -> KeyIterator: Bottle Cap
ArrayDeque -> DeqIterator: Lamp

What this code does

  • The loop only knows Collection and Iterator. Each collection's iterator() decides which iterator class to create, which is exactly the Factory Method idea.
  • The iterator class names are internal JDK details and can differ between Java versions; the items and their order are what the program relies on.

The difference from a simple factory: the choice is made by which subclass you use, not by a key passed to a switch. The JDK uses it everywhere: Collection.iterator() is a factory method, and each collection creates its own iterator class.

Fix the error

Complete the Factory Method

Pick the line that makes this compile.

Every subclass must supply the creation method.

abstract class CheckoutFlow {
protected abstract PaymentMethod createPayment();
}
class UpiCheckout extends CheckoutFlow { }

Error

UpiCheckout.java:5: error: UpiCheckout is not abstract and does not override abstract method createPayment() in CheckoutFlow
class UpiCheckout extends CheckoutFlow { }
^

Adding a new payment type: counting files touched

Count what changes when ShopLite adds wallet payments with each design.

Example 5 · Adding WalletPayment with a registry

PaymentRegistryDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;import java.util.Set;import java.util.function.Supplier;
interface PaymentMethod {    String pay(double amount);}
class CardPayment implements PaymentMethod {    public String pay(double amount) { return String.format("charged Rs %.2f to card", amount); }}
class UpiPayment implements PaymentMethod {    public String pay(double amount) { return String.format("sent a UPI collect request for Rs %.2f", amount); }}
// The new payment type: one new class...class WalletPayment implements PaymentMethod {    public String pay(double amount) { return String.format("paid Rs %.2f from ShopLite wallet", amount); }}
class PaymentRegistry {    private final Map<String, Supplier<PaymentMethod>> makers = new LinkedHashMap<>();
    void register(String type, Supplier<PaymentMethod> maker) {        makers.put(type, maker);    }
    PaymentMethod create(String type) {        Supplier<PaymentMethod> maker = makers.get(type);        if (maker == null) throw new IllegalArgumentException("Unknown payment type: " + type);        return maker.get();    }
    Set<String> types() {        return makers.keySet();    }}
public class PaymentRegistryDemo {    public static void main(String[] args) {        PaymentRegistry payments = new PaymentRegistry();        payments.register("CARD", CardPayment::new);        payments.register("UPI", UpiPayment::new);        payments.register("WALLET", WalletPayment::new);   // ...and one line here
        System.out.println("Types: " + payments.types());        for (String type : payments.types()) {            System.out.println(type + " -> " + payments.create(type).pay(500));        }    }}
Output
Types: [CARD, UPI, WALLET]
CARD -> charged Rs 500.00 to card
UPI -> sent a UPI collect request for Rs 500.00
WALLET -> paid Rs 500.00 from ShopLite wallet

What this code does

  • The registry maps each key to a Supplier, here a constructor reference such as CardPayment::new, so it holds no switch at all.
  • Adding the wallet took one new class and one register line in main; no existing class was edited.

What changes for a new payment type:

  • Scattered new: one new class plus an edit in every place that chooses (checkout, renewals, refunds).
  • Simple factory: one new class plus one new case in the factory.
  • Factory Method: one new product class plus one new subclass, and no edits to existing code.
  • Registry of suppliers: one new class plus one register line in main.

The simple factory is usually the right balance. Use Factory Method when the steps around creation are shared and the subclasses already exist for other reasons, and a registry when types are added often or by plugins.

Next step

Check your understanding

10 quick questions