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.
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.
- 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.
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.
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(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.
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.
- 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 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.
- 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.
- 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.
- 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