CSE Roadmap

Common tier · about 2 hours · 6 parts

Part 4 of 6 · 2 min read

Benefits and liabilities

What it buys and what it costs.

GoF lists four consequences.

  1. It shields the client from implementation classes. Product class names stay inside the concrete factories and never show up in client code.
  2. Swapping families is simple. The concrete factory is named once in the program, where it is built, so changing families means changing that one object.
  3. It promotes consistency. Objects of one family are designed to work together, and a client that takes all its products from one factory cannot mix families by accident.
  4. Supporting new kinds of products is difficult. The interface fixes which products exist. A new kind, such as a Rounding rule, needs a new method on it and an edit to every concrete factory.

The fourth point decides when to use it. The pattern suits a design where families vary and the kinds of product are stable. If new kinds are added often and families rarely, it is a poor fit.

GoF also gives two implementation notes. An application usually needs only one instance of a concrete factory, so factories are often singletons (module 4). And the factory methods are usually implemented with Factory Method, one per product.

Abstract Factory is also the answer to a common interview prompt: "the system must support two themes or two vendors, and the parts must match". Draw the interface, two factories and a client, and name the weakness.

Common mistake

Using an abstract factory for a single product. With one product and many variants, a simple factory or a Factory Method is enough.

Interview angle

Answer in your head first, then open it.

What is Abstract Factory?

An interface for creating families of related objects without naming their concrete classes.

How does it differ from Factory Method?

Factory Method creates one product by overriding a method in a subclass. Abstract Factory creates a set of related products through an object.

What is its main weakness?

Adding a new kind of product changes the interface and all factories.

Check yourself: 1. What happens when a new kind of product is added? 2. Why is it hard to mix families by accident?