CSE Roadmap

Common tier · about 2 hours · 6 parts

Part 3 of 6 · 2 min read

The pattern

One factory interface, many creation methods.

GoF's intent for Abstract Factory is to offer one interface that builds a whole set of related objects, with no mention of their concrete classes. It lists these parts.

  • AbstractFactory declares one creation method for each kind of product.
  • ConcreteFactory implements those methods for one family.
  • AbstractProduct is the interface for one kind of product.
  • ConcreteProduct is a product made by one concrete factory.
  • Client uses only the abstract factory and abstract products.

Here is the billing example.

interface Tax       { long tax(long amount); }
interface Formatter { String format(long amount); }

interface RegionFactory {
    Tax createTax();
    Formatter createFormatter();
}

class GstTax implements Tax { public long tax(long a) { return a * 18 / 100; } }
class RupeeFormatter implements Formatter { public String format(long a) { return "Rs " + a; } }

class SalesTax implements Tax { public long tax(long a) { return a * 8 / 100; } }
class DollarFormatter implements Formatter { public String format(long a) { return "$" + a; } }

class IndiaFactory implements RegionFactory {
    public Tax createTax() { return new GstTax(); }
    public Formatter createFormatter() { return new RupeeFormatter(); }
}

class UsFactory implements RegionFactory {
    public Tax createTax() { return new SalesTax(); }
    public Formatter createFormatter() { return new DollarFormatter(); }
}

class Invoice {
    private final Tax tax;
    private final Formatter fmt;

    Invoice(RegionFactory f) { tax = f.createTax(); fmt = f.createFormatter(); }

    String total(long amount) { return fmt.format(amount + tax.tax(amount)); }
}

For an amount of 1000 (made up), new Invoice(new IndiaFactory()).total(1000) returns "Rs 1180", since 18 percent of 1000 is 180. new Invoice(new UsFactory()).total(1000) returns "$1080", since 8 percent is 80.

Invoice never names GstTax or RupeeFormatter. It receives a factory and asks it for what it needs. This is dependency injection (module 6 of this level) and dependency inversion (Level 2, module 5) at work. CA notes that creating objects normally needs the name of a concrete class, and that an abstract factory is the usual way to keep that name out of the important code.

Abstract factory

An abstract factory is an interface with one creation method per kind of product, so that a client can make a whole product family without naming concrete classes.

Example: RegionFactory with createTax and createFormatter.

Check yourself: 1. What does new Invoice(new UsFactory()).total(1000) return? 2. Which class in the example is the client? 3. How many creation methods does the abstract factory have, and why?