Abstract Factory Pattern
One factory object creates a whole family of parts that are made to go together, so a client never mixes a light button with a dark checkbox.
Overview
Abstract Factory is a creational pattern from the Gang of Four book (Gamma, Helm, Johnson and Vlissides, *Design Patterns*, 1994). Where Factory Method creates one product, Abstract Factory creates a set of products that belong together: every widget of one theme, every driver piece for one database, every parser for one file format.
The client holds one factory object and asks it for each part. Because one factory makes every part, the parts always match. Swapping the family means handing the client a different factory; the client's code does not change.
Interviewers use this pattern to see whether you can tell it apart from Factory Method, whether you know its one real weakness (adding a new kind of product touches every factory), and whether you can explain where the factory gets chosen.
The shape of the pattern
The pattern has five roles, and the client sits on the interface side of all of them.
Each concrete factory returns its own products: LightTheme makes a LightButton and a LightCheckbox, DarkTheme makes the dark pair. Those four classes are left off the drawing to keep it readable. Here are all five roles with their names in the example.
- Abstract factory: ThemeFactory, with one creation method per kind of part.
- Concrete factory: LightTheme and DarkTheme, one per family.
- Abstract product: Button and Checkbox, one per kind of part.
- Concrete product: LightButton, DarkButton, LightCheckbox and DarkCheckbox.
- Client: render_login(factory), which uses only the interfaces.
Interview questions
- How does Abstract Factory stop a client from mixing families?
- Abstract Factory or Factory Method: how do you choose?
- What is the main drawback of Abstract Factory, and how do you soften it?
- How do you pick the concrete factory at runtime, and how do you test the client?
- Draw the roles for a database access layer that supports two databases.
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio