SyntaxPilot
Courses/Low-Level Design/Lesson 24

Low-Level Design · Lesson 24 of 90 · 11 min

Abstract Factory pattern

Abstract Factoryproduct familiesabstract productsconcrete factoriesconsistency between productsAbstract Factory vs Factory Methodcross-platform UI theme exampleadding a new family vs adding a new product

These are the notes for Low-Level Design (LLD) episode 24. Last episode, a factory created one object. Today a factory creates a whole family of objects that must be used together. We start with a thali that doesn't match, watch a dark-mode screen show one white checkbox, invent the Abstract Factory (an interface with one creation method per product), name its roles (abstract factory, concrete factories, abstract products, concrete products, client), swap whole families at runtime, and learn the key trade-off: adding a new family is easy, adding a new product is costly. Finally: Abstract Factory vs Factory Method, and when the pattern is overkill. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs and error messages are real.

1. The real-life idea: a thali is a matching set

At a restaurant In code
South Indian thali: rice, sambar, payasam A product family: objects made to be used together
North Indian thali: roti, dal, gulab jamun Another family: the same slots, different items
Roti + sambar + payasam on one plate Mixed families: each object works, together they clash
"One thali, please": the kitchen fills every slot An abstract factory: one choice creates the whole set

A product family is a set of related objects designed to be used together (a light button with a light checkbox). Each slot on the plate (main, curry, sweet) is a product; each thali fills every slot from one family.

2. The problem in code: a dark screen with a white checkbox

Priya builds a food-ordering app with a light and a dark theme. Button and Checkbox are interfaces with a draw() method; each theme has its own classes. The checkout screen picks each widget separately, with its own theme check. The ? : is the conditional (ternary) operator: condition ? a : b gives a if the condition is true, otherwise b. One widget reads an old setting:

interface Button { String draw(); }     interface Checkbox { String draw(); }     // abstract products
class LightButton implements Button { public String draw() { return "Button: black on white"; } }
class LightCheckbox implements Checkbox { public String draw() { return "Checkbox: black on white"; } }
class DarkButton implements Button { public String draw() { return "Button: white on black"; } }
class DarkCheckbox implements Checkbox { public String draw() { return "Checkbox: white on black"; } }

public class Main {
    static String theme = "dark";                    // the user's new setting
    static String oldTheme = "light";                // a setting from last year's code
    public static void main(String[] args) {
        Button pay = theme.equals("dark") ? new DarkButton() : new LightButton();
        Checkbox tip = oldTheme.equals("dark") ? new DarkCheckbox() : new LightCheckbox();
        Button cancel = theme.equals("dark") ? new DarkButton() : new LightButton();
        System.out.println(pay.draw());
        System.out.println(tip.draw());
        System.out.println(cancel.draw());
    }
}
Button: white on black
Checkbox: black on white
Button: white on black

Every class works, and the screen still looks broken.

Why it broke

  • The theme decision is repeated for every widget: three widgets, three decisions, three chances to get one wrong.
  • Nothing in the code says these objects belong together.
  • One wrong check gives a mixed set, with no error at all.

What we want: choose the family once, and get every widget from that family.

3. The fix: one factory for the whole family

interface Button { String draw(); }     interface Checkbox { String draw(); }     // abstract products
class LightButton implements Button { public String draw() { return "Button: black on white"; } }
class LightCheckbox implements Checkbox { public String draw() { return "Checkbox: black on white"; } }
class DarkButton implements Button { public String draw() { return "Button: white on black"; } }
class DarkCheckbox implements Checkbox { public String draw() { return "Checkbox: white on black"; } }
interface UiFactory { Button button(); Checkbox checkbox(); }   // the abstract factory
class LightFactory implements UiFactory {            // concrete factory: light family
    public Button button() { return new LightButton(); }
    public Checkbox checkbox() { return new LightCheckbox(); }
}
class DarkFactory implements UiFactory {             // concrete factory: dark family
    public Button button() { return new DarkButton(); }
    public Checkbox checkbox() { return new DarkCheckbox(); }
}
public class Main {
    static void checkout(UiFactory ui) {             // knows only UiFactory
        System.out.println(ui.button().draw() + " | " + ui.checkbox().draw());
    }
    public static void main(String[] args) {
        String theme = "dark";
        UiFactory ui = theme.equals("dark") ? new DarkFactory() : new LightFactory();   // chosen ONCE
        checkout(ui);
        checkout(new LightFactory());
    }
}
Button: white on black | Checkbox: white on black
Button: black on white | Checkbox: black on white
  • UiFactory is the abstract factory: an interface with one creation method per product (button(), checkbox()). "Abstract" because it only says what can be made, not how.
  • LightFactory and DarkFactory are concrete factories, one per family. Each makes only its own family's objects.
  • Button and Checkbox are the abstract products (one interface per slot); LightButton, DarkCheckbox and so on are the concrete products.
  • checkout() is the client: it knows only UiFactory, Button and Checkbox, never a Light or Dark class. The theme is checked in exactly one line.

A wrong-family widget is now impossible, because the screen gets every widget from one factory.

4. It has a name: Abstract Factory

The Gang of Four intent: "Provide an interface for creating families of related or dependent objects without specifying their concrete classes." It is a creational pattern.

                 «interface» UiFactory          (abstract factory)
                 + button(): Button
                 + checkbox(): Checkbox
                  ▲                 ▲
       implements ┆                 ┆ implements
        LightFactory             DarkFactory      (concrete factories)
         │ creates                 │ creates
         ▼                         ▼
  LightButton, LightCheckbox   DarkButton, DarkCheckbox   (concrete products)
         ┆ implement Button / Checkbox                    (abstract products)

  checkout(UiFactory ui) ┄┄uses┄┄▶ UiFactory              (client)
Template part Abstract Factory
Intent Create families of related objects without naming their concrete classes
Problem Objects from different families get mixed; the family choice is repeated
Solution An interface with one creation method per product; one concrete factory per family
Participants Abstract factory, concrete factories, abstract products, concrete products, client
Consequences + consistency, families swappable (even at runtime), new families easy; − new products costly, more classes

5. Swapping a whole family at runtime

Because the client only knows the interface, the family can change while the program is running. A small helper turns a setting's name into a concrete factory (it is itself a simple factory, from episode 23, that makes factories):

interface Button { String draw(); }     interface Checkbox { String draw(); }     // abstract products
class LightButton implements Button { public String draw() { return "Button: black on white"; } }
class LightCheckbox implements Checkbox { public String draw() { return "Checkbox: black on white"; } }
class DarkButton implements Button { public String draw() { return "Button: white on black"; } }
class DarkCheckbox implements Checkbox { public String draw() { return "Checkbox: white on black"; } }
interface UiFactory { Button button(); Checkbox checkbox(); }   // the abstract factory
class LightFactory implements UiFactory {            // concrete factory: light family
    public Button button() { return new LightButton(); }
    public Checkbox checkbox() { return new LightCheckbox(); }
}
class DarkFactory implements UiFactory {             // concrete factory: dark family
    public Button button() { return new DarkButton(); }
    public Checkbox checkbox() { return new DarkCheckbox(); }
}
public class Main {
    static void checkout(UiFactory ui) {             // knows only UiFactory
        System.out.println(ui.button().draw() + " | " + ui.checkbox().draw());
    }
    static UiFactory theme(String name) {            // picks the concrete factory
        if (name.equals("light")) return new LightFactory();
        if (name.equals("dark")) return new DarkFactory();
        throw new IllegalArgumentException("no theme: " + name);
    }
    public static void main(String[] args) {
        String[] taps = {"light", "dark", "light", "blue"};        // the user taps the toggle
        for (String tap : taps) { System.out.print(tap + " -> "); checkout(theme(tap)); }
    }
}
light -> Button: black on white | Checkbox: black on white
dark -> Button: white on black | Checkbox: white on black
light -> Button: black on white | Checkbox: black on white
blue -> Exception in thread "main" java.lang.IllegalArgumentException: no theme: blue
    at Main.theme(Main.java:22)
    at Main.main(Main.java:26)

Each screen is fully consistent, and an unknown theme fails loudly instead of drawing a half-themed screen.

Where is the concrete factory chosen?

  • In exactly one place that turns a setting into a factory. Everything after that sees only UiFactory.
  • That place is the composition root (episode 16): the spot near the start of the program where objects are created and wired together.
  • Every other class receives a UiFactory through its constructor or a parameter: dependency injection.
  • An app usually needs only one DarkFactory, so a concrete factory is often a Singleton (episode 22). Patterns combine.

6. Adding a new family: easy

A high-contrast theme (yellow on black, bold and big) for users who find low contrast hard to read is a new family: two new product classes and one new factory. checkout() is not edited.

interface Button { String draw(); }     interface Checkbox { String draw(); }     // abstract products
class LightButton implements Button { public String draw() { return "Button: black on white"; } }
class LightCheckbox implements Checkbox { public String draw() { return "Checkbox: black on white"; } }
class DarkButton implements Button { public String draw() { return "Button: white on black"; } }
class DarkCheckbox implements Checkbox { public String draw() { return "Checkbox: white on black"; } }
interface UiFactory { Button button(); Checkbox checkbox(); }   // the abstract factory
class LightFactory implements UiFactory {            // concrete factory: light family
    public Button button() { return new LightButton(); }
    public Checkbox checkbox() { return new LightCheckbox(); }
}
class DarkFactory implements UiFactory {             // concrete factory: dark family
    public Button button() { return new DarkButton(); }
    public Checkbox checkbox() { return new DarkCheckbox(); }
}
class HcButton implements Button { public String draw() { return "Button: yellow on black, bold"; } }
class HcCheckbox implements Checkbox { public String draw() { return "Checkbox: yellow on black, big"; } }
class HighContrastFactory implements UiFactory {     // a NEW family: one new class
    public Button button() { return new HcButton(); }   public Checkbox checkbox() { return new HcCheckbox(); }
}
public class Main {
    static void checkout(UiFactory ui) {             // knows only UiFactory
        System.out.println(ui.button().draw() + " | " + ui.checkbox().draw());
    }
    public static void main(String[] args) {
        UiFactory[] themes = { new LightFactory(), new DarkFactory(), new HighContrastFactory() };
        for (UiFactory ui : themes) checkout(ui);    // checkout() not edited
    }
}
Button: black on white | Checkbox: black on white
Button: white on black | Checkbox: white on black
Button: yellow on black, bold | Checkbox: yellow on black, big

New family = only new classes, no edits to old code: the open-closed principle (episode 13).

7. Adding a new product: costly

A slider for the tip amount is a new product (a new slot on the thali). The abstract factory gains a method, so every concrete factory breaks:

interface Button { String draw(); }     interface Checkbox { String draw(); }     // abstract products
class LightButton implements Button { public String draw() { return "Button: black on white"; } }
class LightCheckbox implements Checkbox { public String draw() { return "Checkbox: black on white"; } }
class DarkButton implements Button { public String draw() { return "Button: white on black"; } }
class DarkCheckbox implements Checkbox { public String draw() { return "Checkbox: white on black"; } }
interface Slider { String draw(); }                  // a NEW product
interface UiFactory {
    Button button();
    Checkbox checkbox();
    Slider slider();                                 // every factory must now make one
}
class LightFactory implements UiFactory {            // concrete factory: light family
    public Button button() { return new LightButton(); }
    public Checkbox checkbox() { return new LightCheckbox(); }
}
class DarkFactory implements UiFactory {             // concrete factory: dark family
    public Button button() { return new DarkButton(); }
    public Checkbox checkbox() { return new DarkCheckbox(); }
}
public class Main {
    static void checkout(UiFactory ui) {             // knows only UiFactory
        System.out.println(ui.button().draw() + " | " + ui.checkbox().draw());
    }
    public static void main(String[] args) {
        checkout(new DarkFactory());
    }
}
Main.java:12: error: LightFactory is not abstract and does not override abstract method slider() in UiFactory
class LightFactory implements UiFactory {            // concrete factory: light family
^
Main.java:16: error: DarkFactory is not abstract and does not override abstract method slider() in UiFactory
class DarkFactory implements UiFactory {             // concrete factory: dark family
^
2 errors

You must add slider() to every factory, plus a LightSlider, a DarkSlider, and so on.

Change Cost with Abstract Factory
New family (Sepia, HighContrast) Easy: add classes, edit nothing
New product (Slider, TextBox) Costly: change the interface and edit every concrete factory

So use Abstract Factory when families change often but the list of products is stable. (A trade-off means you gain one thing and pay with another.) A default method on the interface can soften a new product, but only if a sensible shared default exists; otherwise each family really does need its own version.

A second family example: payment kits

Families are not only about looks. A UPI payment needs a UPI check (an ID with @) and a UPI receipt; a card payment needs a 16-digit check and a receipt that shows only the last four digits. PaymentKit is the abstract factory; each kit returns its two products as lambdas (episode 5: a short way to write an object with just one method), so each lambda is a concrete product.

interface Validator { boolean ok(String id); }                  // product 1
interface Receipt { String print(int rs, String id); }           // product 2
interface PaymentKit { Validator validator(); Receipt receipt(); }   // abstract factory
class UpiKit implements PaymentKit {
    public Validator validator() { return id -> id.contains("@"); }
    public Receipt receipt() { return (rs, id) -> "UPI receipt: Rs " + rs + " to " + id; }
}
class CardKit implements PaymentKit {
    public Validator validator() { return id -> id.replace(" ", "").length() == 16; }
    public Receipt receipt() { return (rs, id) -> "Card receipt: Rs " + rs + ", card *" + id.substring(15); }
}
public class Main {
    static String pay(PaymentKit kit, int rs, String id) {
        return kit.validator().ok(id) ? kit.receipt().print(rs, id) : "rejected: " + id;
    }
    public static void main(String[] args) {
        System.out.println(pay(new UpiKit(), 240, "priya@upi"));
        System.out.println(pay(new CardKit(), 240, "4111 1111 1111 1234"));
        System.out.println(pay(new UpiKit(), 240, "4111 1111 1111 1234"));
    }
}
UPI receipt: Rs 240 to priya@upi
Card receipt: Rs 240, card *1234
rejected: 4111 1111 1111 1234

pay() gets both parts from one kit, so a UPI check can never be paired with a card receipt. (The mini project below builds the same thing with named classes.)

8. Abstract Factory vs Factory Method

Factory Method (episode 23) Abstract Factory
Creates One product A family of related products
Shape An abstract creator with one overridable creation method An interface with several creation methods
Works through Inheritance: a subclass decides Composition (episode 11): a factory object is passed in and can be swapped
Example HillDelivery.createVehicle() returns a Jeep DarkFactory.button() + DarkFactory.checkbox()
Adding a variant A new subclass A new concrete factory (a whole family)

They combine: each creation method of an abstract factory is a factory method, and each concrete factory overrides them for its family.

9. When to use it, and when not

Use it when objects must be used together, one family at a time:

  • Themes: light / dark / high contrast.
  • Cross-platform apps: an app that runs on Android and on iPhone wants native-looking widgets on each, so each platform is a family.
  • Back-ends: a fast fake database family for tests vs the real one in production.

Avoid it when:

  • There is only one family: it's just extra classes (pattern overuse, episode 21).
  • New products arrive every week: every factory breaks each time.

Common mistakes

Mistake Exact message / symptom Why Fix
A theme check per widget Checkbox: black on white on a dark screen The family is chosen many times Choose one UiFactory, once
Client code calls new DarkButton() no error, but the theme can't be swapped Client tied to concrete products Ask the factory: ui.button()
Adding slider() to UiFactory error: LightFactory is not abstract and does not override abstract method slider() in UiFactory (and the same for DarkFactory) Every factory must now make the new product Implement it in every factory
Unknown theme name IllegalArgumentException: no theme: blue No factory for that name Validate settings; offer known themes
Abstract Factory for one family no error: extra classes for nothing Pattern overuse Just use the classes
A factory that mixes families e.g. DarkFactory.checkbox() returns new LightCheckbox() Defeats the purpose One family per concrete factory; test each factory

Mini project: a payment kit family

A UPI payment needs a UPI-style validator (an ID with @) and a UPI receipt; a card payment needs a card validator (16 digits) and a card receipt that shows only the last 4 digits. Mixing them (a UPI validator with a card receipt) must be impossible. Build it with an abstract factory PaymentKit.

Solution
interface Validator { boolean valid(String id); }
interface Receipt { String print(int rupees, String id); }

class UpiValidator implements Validator { public boolean valid(String id) { return id.contains("@"); } }
class UpiReceipt implements Receipt { public String print(int r, String id) { return "UPI receipt: Rs " + r + " to " + id; } }
class CardValidator implements Validator { public boolean valid(String id) { return id.replace(" ", "").length() == 16; } }
class CardReceipt implements Receipt {
    public String print(int r, String id) { return "Card receipt: Rs " + r + " on card ending " + id.substring(id.length() - 4); }
}
interface PaymentKit { Validator validator(); Receipt receipt(); }     // the abstract factory
class UpiKit implements PaymentKit {
    public Validator validator() { return new UpiValidator(); }
    public Receipt receipt() { return new UpiReceipt(); }
}
class CardKit implements PaymentKit {
    public Validator validator() { return new CardValidator(); }
    public Receipt receipt() { return new CardReceipt(); }
}
public class Main {
    static String checkout(PaymentKit kit, int rupees, String id) {
        if (!kit.validator().valid(id)) return "rejected: " + id;
        return kit.receipt().print(rupees, id);
    }
    public static void main(String[] args) {
        System.out.println(checkout(new UpiKit(), 240, "priya@upi"));
        System.out.println(checkout(new CardKit(), 240, "4111 1111 1111 1234"));
        System.out.println(checkout(new UpiKit(), 240, "4111 1111 1111 1234"));
    }
}
UPI receipt: Rs 240 to priya@upi
Card receipt: Rs 240 on card ending 1234
rejected: 4111 1111 1111 1234

checkout() can't mix a UPI validator with a card receipt, because both come from the same kit.

Practice

1. Add a Sepia theme to the UI code. Which existing classes change?

Answer

None. Add SepiaButton, SepiaCheckbox and SepiaFactory implements UiFactory.

2. Add a TextBox product. List every class you must create or edit.

Answer

Create interface TextBox, LightTextBox, DarkTextBox (and one per other family); edit UiFactory (add TextBox textBox();) and every concrete factory (LightFactory, DarkFactory, ...). The compiler lists each factory you missed.

3. Explain Abstract Factory vs Factory Method in three sentences.

Answer

Factory Method creates one product: an abstract creator declares a creation method and subclasses override it (inheritance). Abstract Factory creates a family of related products through one object with several creation methods, which is passed in and can be swapped (composition). Each method of an abstract factory is itself a factory method.

4. Why does checkout(UiFactory ui) make the screen easy to test?

Answer

A test can pass a fake factory that returns simple stub widgets (or records what was created), without touching the real light or dark classes.

5. Your app has one theme and no plans for more. Should you add an abstract factory?

Answer

No. With one family there is nothing to keep consistent or swap; the pattern would only add classes. Add it when a second family actually appears.

Quick quiz

interface UiFactory {
    Button button();
    Checkbox checkbox();
}
// LightFactory, DarkFactory and
// HighContrastFactory implement it.

// New requirement: add a Sepia theme
// (sepia button + sepia checkbox).

How many existing classes must you edit?

  • A. 0 existing classes
  • B. 1: UiFactory
  • C. 3: every factory
  • D. 4: UiFactory + every factory
Answer

A. 0. A new theme is a new family: add SepiaButton, SepiaCheckbox and SepiaFactory. A new product would be D.

Interview questions

  1. What is the Abstract Factory pattern? A creational pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes.
  2. What problem does it solve? It keeps objects from one family together (no mixed families) and lets the whole family be swapped by changing one object.
  3. Name its participants. Abstract factory, concrete factories, abstract products, concrete products, client.
  4. Abstract Factory vs Factory Method? One product via subclass override (inheritance) vs a family of products via an injected factory object (composition); AF's methods are factory methods.
  5. What's easy and what's hard to change? New families are easy (new classes only); new products are hard (the interface and every concrete factory change).
  6. Real examples? UI themes or look-and-feels, cross-platform widget sets, database or cloud-provider families, test vs production back-ends.
  7. Where should the concrete factory be chosen? Once, in the composition root, from configuration; everything else receives the abstract factory.
  8. Why is a concrete factory often a Singleton? It usually has no state and one is enough for the whole app.
  9. Downsides? More classes and indirection; harder to add products; overkill with one family.

Glossary

Term Meaning, with an example
Abstract Factory GoF pattern: an interface for creating families of related objects. UiFactory
Product family Related objects designed to be used together. DarkButton + DarkCheckbox
Product One kind of object a factory creates (a slot). Button, Checkbox
Abstract product The interface for one product. Button
Concrete product One family's class for a product. DarkButton (or a lambda, as in UpiKit)
Lambda A short way to write an object with one method (episode 5). id -> id.contains("@")
Abstract factory (role) The interface with one creation method per product. UiFactory
Concrete factory A factory that makes every product of one family. DarkFactory
Client Code that uses only the abstract factory and abstract products. checkout()
Consistency between products The guarantee that all objects come from the same family
Conditional (ternary) operator cond ? a : b gives a if cond is true, else b
Theme A family of look-and-feel choices. Light, dark, high contrast
High contrast Strong colour difference (yellow on black) for readability
Cross-platform Running on several platforms (Android, iPhone) with native-looking parts on each
Runtime swap Changing the family while the program runs by passing another factory
Composition root The one place where objects are created and wired together (episode 16)
Dependency injection Passing dependencies in instead of creating them inside (episode 16)
Composition Using an object you hold, instead of inheriting (episode 11)
Factory Method GoF pattern: subclasses decide which single product to create (episode 23)
Trade-off Gaining one thing by paying with another
Open-closed principle Add behaviour without editing existing code (episode 13)
Pattern overuse Using a pattern where no problem exists (episode 21)

Summary

  • A product family is a set of objects made to be used together; mixing families breaks the app without any error.
  • The abstract factory is an interface with one creation method per product; each concrete factory makes one whole family.
  • The client knows only interfaces, so swapping the factory swaps the whole family, even at runtime; choose it once, in the composition root.
  • New family = easy (new classes only); new product = costly (edit the interface and every factory).
  • Factory Method: one product, by inheritance. Abstract Factory: a family, by composition; its methods are factory methods.
  • Don't use it for a single family.

Next episode: The Builder pattern.