LOW-LEVEL DESIGN · CREATIONAL PATTERNS · CREATIONAL · 24 OF 48

Abstract Factory Pattern in Java: Families of Objects That Match

The Abstract Factory pattern with a checkout that runs in two countries: one factory object creates a matching payment rail, tax rule and money format, so families can never be mixed. Covers the participants, Java code, choosing the factory once at startup, adding a family versus adding a product, and how it differs from factory method and builder.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 15

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 128 lines, with a small main() demo. Save it as RegionKitAbstractFactoryDemo.java, then run javac RegionKitAbstractFactoryDemo.java && java RegionKitAbstractFactoryDemo.

import java.util.Locale;

/** Abstract factory with a checkout in two countries: one kit creates a matching family of objects. */
public class RegionKitAbstractFactoryDemo {

    // ---------- the products ----------
    interface PaymentRail {
        String collect(double amount);
    }

    interface TaxRule {
        double taxOn(double net);
    }

    interface MoneyFormat {
        String show(double amount);
    }

    static String twoDecimals(double amount) {
        return String.format(Locale.ROOT, "%.2f", amount);
    }

    // India family
    static final class UpiRail implements PaymentRail {
        @Override public String collect(double amount) { return "UPI collect request sent"; }
    }

    static final class GstRule implements TaxRule {
        private final double rate;

        GstRule(double rate) { this.rate = rate; }

        @Override public double taxOn(double net) { return net * rate; }
    }

    // Germany family
    static final class SepaRail implements PaymentRail {
        @Override public String collect(double amount) { return "SEPA bank transfer started"; }
    }

    static final class VatRule implements TaxRule {
        private final double rate;

        VatRule(double rate) { this.rate = rate; }

        @Override public double taxOn(double net) { return net * rate; }
    }

    // ---------- the problem: each piece picked by its own condition ----------
    static final class MixedCheckout {
        String pay(String country, double net) {
            PaymentRail rail = country.equals("IN") ? new UpiRail() : new SepaRail();
            // written on another day, with a different condition
            TaxRule tax = country.equals("DE") ? new VatRule(0.19) : new GstRule(0.18);
            double total = net + tax.taxOn(net);
            return rail.collect(total) + ", total " + twoDecimals(total);
        }
    }

    // ---------- the clean version: the abstract factory ----------
    interface RegionKit {
        PaymentRail paymentRail();

        TaxRule taxRule();

        MoneyFormat moneyFormat();
    }

    static final class IndiaKit implements RegionKit {
        @Override public PaymentRail paymentRail() { return new UpiRail(); }

        @Override public TaxRule taxRule() { return new GstRule(0.18); }

        @Override public MoneyFormat moneyFormat() { return amount -> "Rs " + twoDecimals(amount); }
    }

    static final class GermanyKit implements RegionKit {
        @Override public PaymentRail paymentRail() { return new SepaRail(); }

        @Override public TaxRule taxRule() { return new VatRule(0.19); }

        @Override public MoneyFormat moneyFormat() { return amount -> "EUR " + twoDecimals(amount); }
    }

    /** The only place that switches on the country. Unknown codes fail loudly. */
    static RegionKit kitFor(String countryCode) {
        return switch (countryCode.toUpperCase(Locale.ROOT)) {
            case "IN" -> new IndiaKit();
            case "DE" -> new GermanyKit();
            default -> throw new IllegalArgumentException("no region kit for " + countryCode);
        };
    }

    // ---------- the client: no country names, no ifs ----------
    static final class CheckoutService {
        private final PaymentRail rail;
        private final TaxRule tax;
        private final MoneyFormat money;

        CheckoutService(RegionKit kit) {
            this.rail = kit.paymentRail();     // all three pieces come from the same kit,
            this.tax = kit.taxRule();          // so they always belong to the same family
            this.money = kit.moneyFormat();
        }

        String pay(double net) {
            double total = net + tax.taxOn(net);
            return rail.collect(total) + ", total " + money.show(total);
        }
    }

    public static void main(String[] args) {
        System.out.println("Mixed version with country \"de\":");
        System.out.println("  " + new MixedCheckout().pay("de", 1000) + "   <- SEPA with 18% Indian GST!");

        System.out.println("Abstract factory:");
        for (String code : new String[] {"IN", "de"}) {
            CheckoutService checkout = new CheckoutService(kitFor(code));
            System.out.println("  " + code + ": " + checkout.pay(1000));
        }

        try {
            kitFor("XX");
        } catch (IllegalArgumentException e) {
            System.out.println("  XX: " + e.getMessage());
        }
    }
}

Notes

The problem

Here is the naive code. The payment rail is chosen by one condition, and the tax rule by another, written on a different day by a different person. Pass the country as lowercase d e, and the first check says not India, so SEPA. The second check says not Germany, so Indian G S T. You now charge a German customer eighteen percent Indian tax through a euro bank transfer. Nothing in the types stops it.

MixedCheckout
PaymentRail rail = country.equals("IN")
    ? new UpiRail() : new SepaRail();
TaxRule tax = country.equals("DE")
    ? new VatRule() : new GstRule();

// country = "de" (lowercase):
//   rail = SEPA, tax = GST 18%
// a German order taxed as Indian

The idea

The idea in plain words: one interface with a create method for each kind of product. Each implementation of that interface builds one whole family. The client chooses a factory once, and from then on asks that same factory for every piece. Since one factory only knows its own family, the pieces always match. You make the choice in one place instead of in many scattered if statements.

Abstract factory
  • an interface with one create
  • method per product type
  • each implementation creates
  • one whole family
  • the client picks a factory
  • once, then asks it for every
  • piece, so pieces always match

The participants

The full picture. Region kit is the abstract factory. India kit and Germany kit are the concrete factories. Payment rail and tax rule are the abstract products. The top row, U P I rail and G S T rule, is the India family. The bottom row, SEPA rail and VAT rule, is the Germany family. Checkout service, the client, only depends on the middle row of interfaces. It never names a concrete country class.

Code: the factory

In code, there are three small product interfaces. Payment rail collects an amount. Tax rule works out tax on a net amount. Money format turns a number into display text. Region kit has one method for each: payment rail, tax rule and money format. Every return type is an interface, so nothing about India or Germany leaks into this contract. The diagram shows two products to stay readable, but the code has three.

RegionKit
interface PaymentRail {
    String collect(double amount); }
interface TaxRule {
    double taxOn(double net); }
interface MoneyFormat {
    String show(double amount); }

interface RegionKit {
    PaymentRail paymentRail();
    TaxRule taxRule();
    MoneyFormat moneyFormat(); }

Code: a concrete kit

India kit implements region kit. Payment rail returns a U P I rail. Tax rule returns a G S T rule at eighteen percent. Money format shows rupees. Germany kit is the mirror image: SEPA rail, VAT at nineteen percent, and euros. All knowledge of one country sits in one class. When Indian tax rules change, you know exactly which file to open, and it cannot affect Germany.

IndiaKit
final class IndiaKit implements RegionKit {
  public PaymentRail paymentRail() {
    return new UpiRail(); }
  public TaxRule taxRule() {
    return new GstRule(0.18); }
  public MoneyFormat moneyFormat() {
    return amt -> "Rs " + fmt(amt); }
}
// GermanyKit: SepaRail, VatRule(0.19),
//   "EUR " format

Code: the client

Checkout service takes a region kit in its constructor and asks it for all three pieces. Its pay method adds tax to the net amount, collects the total through the rail, and formats it. There is no if statement about countries anywhere in checkout. Because all three pieces came from the same kit, mixing is impossible by construction, not by careful coding.

CheckoutService
CheckoutService(RegionKit kit) {
    this.rail = kit.paymentRail();
    this.tax = kit.taxRule();
    this.money = kit.moneyFormat();
}
String pay(double net) {
    double total = net + tax.taxOn(net);
    return rail.collect(total)
        + " " + money.show(total);
}

Run-through

Follow one order. At startup the app reads the country code once and creates an India kit. Checkout asks it for a tax rule and gets G S T. It asks for a payment rail and gets U P I. A customer pays for a one thousand rupee order. Tax is one hundred and eighty, the total is eleven hundred and eighty, collected by U P I and shown in rupees. Every piece came from the same family.

Picking the kit

Someone still has to choose a kit. That choice happens once, at startup or per request, in a small method with a single switch. Unknown countries throw an error straight away, so a bad code fails loudly instead of silently producing a mixed checkout. Often this method is itself a simple static factory, and in a framework the right kit is injected based on configuration.

Choose once
static RegionKit kitFor(String code) {
  return switch (code.toUpperCase()) {
    case "IN" -> new IndiaKit();
    case "DE" -> new GermanyKit();
    default -> throw new
        IllegalArgumentException(code);
  };
}
// unknown country fails loudly
// instead of mixing quietly

Easy and hard changes

Abstract factory has an important asymmetry. Adding a new family, say the United Kingdom, is easy: one new kit class with its products, and nothing else changes. Adding a new kind of product, say invoice numbering, is hard: you add a method to region kit and must implement it in every single kit. So the pattern fits best when the list of product types is stable and the number of families grows.

The asymmetry
  • add a country (UK):
  • new UkKit + its products
  • nothing else changes
  • add a product type
  • (invoice numbering):
  • add a method to RegionKit
  • implement it in EVERY kit
  • stable product list, growing
  • families: a good fit

When not to use it

Use it when several products must match, when you swap them as a whole, by region, by visual theme or by database vendor, and when tests benefit from a whole fake family. Skip it when there is only one product type, because then factory method or a constructor is enough, when pieces can be mixed freely, or when there will only ever be one family. Otherwise it is many interfaces for no gain.

Use or avoid
  • use when:
  • • several products must match
  • • families are swapped as a
  • whole (region, theme, DB)
  • • you test with a fake family
  • avoid when:
  • • only one product type
  • • pieces mix freely
  • • only one family, ever

In Java

You have used something very close to this. A JDBC connection works like an abstract factory. It has create statement, prepare statement and create blob, and every object it returns belongs to the same driver. A PostgreSQL connection gives you PostgreSQL statements, and a MySQL connection gives you MySQL ones. Your code only sees the interfaces, and you never get a statement from one driver bound to another driver's connection.

Where you see it
  • java.sql.Connection
  • createStatement()
  • prepareStatement(sql)
  • createBlob()
  • a PostgreSQL connection
  • returns PostgreSQL objects,
  • a MySQL connection returns
  • MySQL ones; your code sees
  • only the interfaces

Neighbours

How does it differ from its neighbours? Factory method is one overridable method that creates one product, inside a class that does other work. Abstract factory is a whole object whose only job is creating a family, and you pass it around, which is composition. Builder assembles one complex object step by step. They combine well: each create method inside a kit is often a small factory method.

How it differs
  • factory method:
  • one product, one overridable
  • method, inheritance
  • abstract factory:
  • a family, several methods,
  • an object you pass in
  • builder:
  • one complex object, built
  • step by step
  • kits often USE factory methods

In LLD interviews

In interviews, look for objects that must always change together. Payment providers, where the gateway, the refund client and the webhook parser must all come from the same provider. Visual themes, where the button, chart and font must match. Or storage, where all repositories come from either a SQL kit or an in memory kit for tests. Common mistakes are calling any factory abstract, and building a kit for a single product.

Where it comes up
  • payments per region or
  • provider (gateway + refunds
  • + webhooks)
  • UI themes: button, chart, font
  • storage: SQL vs in-memory
  • repositories for tests
  • mistakes:
  • • calling any factory abstract
  • • a kit for one product

Interview questions

What problem does the abstract factory pattern solve?

It guarantees that related objects which must work together come from the same family. The client picks one factory and gets every product from it, so it cannot accidentally combine, for example, a German tax rule with an Indian payment rail.

What is the difference between abstract factory and factory method?

Factory method is one overridable method that creates one product, and the choice is made by subclassing the class that uses it. Abstract factory is a separate object with several creation methods for a family of products, and the client receives it through composition.

What is the main drawback of abstract factory?

Adding a new product type is expensive: you must add a method to the factory interface and implement it in every concrete factory. Adding a new family is cheap. It also adds many interfaces, which is wasted effort when families never vary.

Where is the concrete factory usually chosen?

In one place, at startup or at the start of a request, often in a small static factory or by dependency injection based on configuration. After that, the client only holds the abstract factory interface and never checks the family again.

Can you give a real Java example close to abstract factory?

A java.sql.Connection creates Statement, PreparedStatement and Blob objects, and all of them belong to the same driver as the connection. Client code uses only the JDBC interfaces, so switching databases changes the family without changing the code.

How does abstract factory help testing?

You can write a fake family, such as an in-memory kit whose products record calls instead of contacting real services, and pass it to the client. The client code is unchanged, and the test stays fast and free of network calls.

Should concrete factories be singletons?

They are usually stateless, so one instance per family is enough, but they do not need the Singleton pattern. Create one at startup and inject it, which keeps the code testable and allows a different kit per request if needed.

When would you use abstract factory in an LLD interview?

When the design has a set of objects that must vary together, such as a payment provider (gateway, refund client, webhook parser), a theme (button, chart, font), or a storage backend (all repositories SQL or all in memory).