Abstract Factory: families of related objects
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite is opening a US store. Indian GST must go with rupees and Indian shipping, never with dollars. How do you make sure a developer cannot mix the two by mistake?
The problem: objects that must match
A family is a group of related products that must be used together, such as one region's tax calculator, currency formatter and shipping calculator.
Each region needs a family of matching objects: a tax calculator, a currency formatter and a shipping calculator. The program below shows what goes wrong when they are picked one by one.
Example 1 · The bug: India tax printed in dollars
class GstCalculator { String label() { return "GST 18%"; } double tax(double amount) { return amount * 0.18; }}
class DollarFormatter { String format(double amount) { return String.format("$%.2f", amount); }}
public class MismatchDemo { public static void main(String[] args) { // Each object was picked in a different file by a different developer GstCalculator tax = new GstCalculator(); // set up for the India store DollarFormatter money = new DollarFormatter(); // copied from the US code path
double amount = 1000; System.out.println("Subtotal: " + money.format(amount)); System.out.println(tax.label() + ": " + money.format(tax.tax(amount))); System.out.println("Nothing stopped Indian GST from being shown in dollars."); }}Subtotal: $1000.00 GST 18%: $180.00 Nothing stopped Indian GST from being shown in dollars.
What this code does
- Both objects are valid on their own; the bug is the combination. The compiler cannot help, because nothing says these two belong to different regions.
- This is the problem Abstract Factory removes: the choice of region is made once, for the whole family.
When each object is chosen separately, in different files, nothing stops a developer from pairing India's tax rule with the US formatter. The bug compiles, runs and prints nonsense on a real receipt.
An AbstractFactory interface with one create method per product
Abstract Factory is an interface for creating a family of related objects without naming their concrete classes. Each concrete factory builds one family.
Abstract Factory has one create method per product. Here is StoreFactory for ShopLite's three products: tax, currency and shipping.
interface StoreFactory { TaxCalculator createTaxCalculator(); CurrencyFormatter createCurrencyFormatter(); ShippingCalculator createShippingCalculator();}Each object the factory makes is a product: TaxCalculator, CurrencyFormatter and ShippingCalculator. Whoever holds a StoreFactory can make every product of one family, and the family is decided by which factory it is.
Order of execution
Build an abstract factory
Put the steps in the order you write them.
IndiaStoreFactory and UsStoreFactory
A concrete factory is a class that implements the factory interface for one family, so all the products it creates match each other.
Each concrete factory builds one family. IndiaStoreFactory and UsStoreFactory below return matching tax, currency and shipping products.
Example 2 · Two store families from two factories
interface TaxCalculator { String label(); double tax(double amount);}
interface CurrencyFormatter { String format(double amount);}
interface ShippingCalculator { double shipping(double amount);}
interface StoreFactory { TaxCalculator createTaxCalculator(); CurrencyFormatter createCurrencyFormatter(); ShippingCalculator createShippingCalculator();}
// India familyclass GstCalculator implements TaxCalculator { public String label() { return "GST 18%"; } public double tax(double amount) { return amount * 0.18; }}
class RupeeFormatter implements CurrencyFormatter { public String format(double amount) { return String.format("Rs %.2f", amount); }}
class IndiaShipping implements ShippingCalculator { public double shipping(double amount) { return amount >= 499 ? 0 : 40; }}
class IndiaStoreFactory implements StoreFactory { public TaxCalculator createTaxCalculator() { return new GstCalculator(); } public CurrencyFormatter createCurrencyFormatter() { return new RupeeFormatter(); } public ShippingCalculator createShippingCalculator() { return new IndiaShipping(); }}
// US familyclass UsSalesTax implements TaxCalculator { public String label() { return "Sales tax 7%"; } public double tax(double amount) { return amount * 0.07; }}
class DollarFormatter implements CurrencyFormatter { public String format(double amount) { return String.format("$%.2f", amount); }}
class UsShipping implements ShippingCalculator { public double shipping(double amount) { return amount >= 35 ? 0 : 5.99; }}
class UsStoreFactory implements StoreFactory { public TaxCalculator createTaxCalculator() { return new UsSalesTax(); } public CurrencyFormatter createCurrencyFormatter() { return new DollarFormatter(); } public ShippingCalculator createShippingCalculator() { return new UsShipping(); }}
public class AbstractFactoryDemo { static void printFamily(String region, StoreFactory store, double amount) { TaxCalculator tax = store.createTaxCalculator(); CurrencyFormatter money = store.createCurrencyFormatter(); ShippingCalculator shipping = store.createShippingCalculator(); System.out.println(region + ": " + tax.label() + " = " + money.format(tax.tax(amount)) + ", shipping " + money.format(shipping.shipping(amount))); }
public static void main(String[] args) { printFamily("India", new IndiaStoreFactory(), 400); printFamily("US", new UsStoreFactory(), 30); }}India: GST 18% = Rs 72.00, shipping Rs 40.00 US: Sales tax 7% = $2.10, shipping $5.99
What this code does
printFamilytakes aStoreFactoryand gets all three products from it, so the tax, the currency and the shipping always come from the same region.- Rs 400 is below the Rs 499 limit and $30 is below the $35 limit, so both orders pay shipping in their own currency.
IndiaStoreFactory returns GST at 18%, a rupee formatter and Indian shipping (free from Rs 499). UsStoreFactory returns 7% sales tax, a dollar formatter and US shipping (free from $35).
The matching rule now lives in the class structure: one factory object cannot hand out a mixed family, as long as callers take all products from it.
Predict the output
Which family answers?
Read the code and pick the exact output.
Round 1 of 2
India: Rs 300 is below the free-shipping limit.
Client code that never names a concrete class
A client is code that uses a factory and its products only through interfaces, never naming a concrete class.
The client is the code that uses the products. CheckoutSummary below receives a StoreFactory and never writes new GstCalculator().
Example 3 · A checkout summary that only knows interfaces
import java.util.List;
interface TaxCalculator { String label(); double tax(double amount);}
interface CurrencyFormatter { String format(double amount);}
interface ShippingCalculator { double shipping(double amount);}
interface StoreFactory { TaxCalculator createTaxCalculator(); CurrencyFormatter createCurrencyFormatter(); ShippingCalculator createShippingCalculator();}
class GstCalculator implements TaxCalculator { public String label() { return "GST 18%"; } public double tax(double amount) { return amount * 0.18; }}
class RupeeFormatter implements CurrencyFormatter { public String format(double amount) { return String.format("Rs %.2f", amount); }}
class IndiaShipping implements ShippingCalculator { public double shipping(double amount) { return amount >= 499 ? 0 : 40; }}
class IndiaStoreFactory implements StoreFactory { public TaxCalculator createTaxCalculator() { return new GstCalculator(); } public CurrencyFormatter createCurrencyFormatter() { return new RupeeFormatter(); } public ShippingCalculator createShippingCalculator() { return new IndiaShipping(); }}
class UsSalesTax implements TaxCalculator { public String label() { return "Sales tax 7%"; } public double tax(double amount) { return amount * 0.07; }}
class DollarFormatter implements CurrencyFormatter { public String format(double amount) { return String.format("$%.2f", amount); }}
class UsShipping implements ShippingCalculator { public double shipping(double amount) { return amount >= 35 ? 0 : 5.99; }}
class UsStoreFactory implements StoreFactory { public TaxCalculator createTaxCalculator() { return new UsSalesTax(); } public CurrencyFormatter createCurrencyFormatter() { return new DollarFormatter(); } public ShippingCalculator createShippingCalculator() { return new UsShipping(); }}
record CartLine(String name, double price, int qty) {}
// The client: only interfaces, never a concrete classclass CheckoutSummary { private final TaxCalculator tax; private final CurrencyFormatter money; private final ShippingCalculator shipping;
CheckoutSummary(StoreFactory store) { this.tax = store.createTaxCalculator(); this.money = store.createCurrencyFormatter(); this.shipping = store.createShippingCalculator(); }
void print(String orderId, List<CartLine> lines) { double subtotal = 0; for (CartLine line : lines) subtotal += line.price() * line.qty(); double t = tax.tax(subtotal); double s = shipping.shipping(subtotal); System.out.println(orderId); System.out.printf(" %-14s %s%n", "Subtotal", money.format(subtotal)); System.out.printf(" %-14s %s%n", tax.label(), money.format(t)); System.out.printf(" %-14s %s%n", "Shipping", money.format(s)); System.out.printf(" %-14s %s%n", "Total", money.format(subtotal + t + s)); }}
// The only place that maps a region to a familyclass StoreFactories { static StoreFactory forRegion(String region) { return switch (region) { case "IN" -> new IndiaStoreFactory(); case "US" -> new UsStoreFactory(); default -> throw new IllegalArgumentException("No store for region " + region); }; }}
public class StoreCheckoutDemo { public static void main(String[] args) { new CheckoutSummary(StoreFactories.forRegion("IN")) .print("ORD-IN-1", List.of(new CartLine("Hoodie", 899, 1), new CartLine("Pen set", 150, 2))); new CheckoutSummary(StoreFactories.forRegion("US")) .print("ORD-US-1", List.of(new CartLine("Notebook", 4.00, 3))); }}ORD-IN-1 Subtotal Rs 1199.00 GST 18% Rs 215.82 Shipping Rs 0.00 Total Rs 1414.82 ORD-US-1 Subtotal $12.00 Sales tax 7% $0.84 Shipping $5.99 Total $18.83
What this code does
CheckoutSummaryis written once and works for both regions; search it for a concrete class name and you will find none.StoreFactories.forRegionis the single place that turns"IN"or"US"into a factory. A UK store would add onecasethere and one new factory.
Common mistake: a new RupeeFormatter() inside the client. One line like that brings the mismatch bug back for every other region, so search the client for concrete class names.
Find the bug
Spot the leak
Each snippet has one wrong line. Tap it, then check the fix.
Every product must come from the factory.
Round 1 of 2The cost: a new product type changes every factory
Adding a family is cheap, but adding a product type is expensive. The program below adds a ReturnPolicy product and shows why.
Example 4 · Adding a ReturnPolicy product to every factory
interface TaxCalculator { String label();}
interface ReturnPolicy { String describe();}
interface StoreFactory { TaxCalculator createTaxCalculator(); ReturnPolicy createReturnPolicy();}
class IndiaStoreFactory implements StoreFactory { public TaxCalculator createTaxCalculator() { return () -> "GST 18%"; } public ReturnPolicy createReturnPolicy() { return () -> "7-day returns, refund to source"; }}
class UsStoreFactory implements StoreFactory { public TaxCalculator createTaxCalculator() { return () -> "Sales tax 7%"; } public ReturnPolicy createReturnPolicy() { return () -> "30-day returns, store credit or refund"; }}
// Before the two createReturnPolicy() methods above were written, javac said:// error: IndiaStoreFactory is not abstract and does not override abstract method// createReturnPolicy() in StoreFactory
public class NewProductCostDemo { public static void main(String[] args) { StoreFactory[] stores = { new IndiaStoreFactory(), new UsStoreFactory() }; String[] names = { "India", "US" }; for (int i = 0; i < stores.length; i++) { System.out.println(names[i] + ": " + stores[i].createTaxCalculator().label() + " | " + stores[i].createReturnPolicy().describe()); } }}India: GST 18% | 7-day returns, refund to source US: Sales tax 7% | 30-day returns, store credit or refund
What this code does
- One new method in
StoreFactoryforced both factories to change; until they did, the compiler reported the error quoted in the comment. - The products here are written as lambdas, because
TaxCalculatorandReturnPolicyeach have one method. That keeps small families short.
Adding a family takes one new factory class and its products. Adding a product type changes the interface, so every concrete factory, including test fakes, must change before the code compiles again.
Choose Abstract Factory when the product list is stable and families are what you add. Factory Method creates one product and lets subclasses choose it; Abstract Factory creates several related products and guarantees they match.
Next step
Check your understanding
10 quick questions