CSE Roadmap

Common tier · about 2 hours · 6 parts

Part 5 of 6 · 1 min read

Wiring it

Choose the family once, at the edge.

Wiring it in a real program

The pattern pays off only when the choice of family is made in one place. A common setup is a small start-up class that reads a setting, such as a region code, and builds the matching factory. Everything else receives the factory through its constructor.

static RegionFactory forRegion(String code) {
    switch (code) {
        case "IN": return new IndiaFactory();
        case "US": return new UsFactory();
        default: throw new IllegalArgumentException("unknown region: " + code);
    }
}

The switch here is the one place that names concrete factories. If it grows, replace it with a map from region code to factory. The rest of the program stays free of region names, so adding a region means adding one factory class and one entry.

A test can pass a fake factory whose tax is always zero, which makes totals easy to check. This is the same benefit as the fake notifier of Level 2, module 5.

In an interview, say where the family is chosen. A diagram that shows the chooser at the edge and the client in the middle gives a clear answer to "where does new happen?".

Check yourself: 1. Where should the family be chosen? 2. How does a fake factory help a test?

Words you will meet

Word Meaning
Product family Related objects designed to be used together
Abstract factory An interface that creates each product of a family
Concrete factory A class that creates the products of one family
Client The code that uses the factory and the products
Variant One version of a family, such as one country