Skip to the guide

Abstract factory

IntermediatePattern7 pages

An abstract factory is one object that makes a whole family of parts that belong together, so the parts always match. The 1994 book, Design Patterns, gives its intent as "provide an interface for creating families of related or dependent objects without specifying their concrete classes." It is rarely the right call in a 45-minute round. Interviewers listen for the one signal that earns it: parts that must match, swapped as a set.

A school uniform shop

Think of a shop that sells uniforms for several schools. A parent says "Greenhill's uniform, age ten", and the assistant takes everything from Greenhill's rack: the shirt, the tie and the blazer, all in Greenhill's colours. The parent makes one choice, and the pieces match because they come from one rack.

Another parent buys the pieces one at a time, from wherever is cheapest. It works, until a child arrives at school in Greenhill's blazer and Oakwood's tie, and nothing in the shopping stopped it. When a child moves school, the first parent changes one word. When a new school opens, the shop adds one rack, and nobody changes how parents shop.

In code, the shop's promise, "one school's whole uniform", is the interface Widgets, and each school's rack is a family, such as MacWidgets. The shirt and the tie are the parts it makes, a Dialog and its Buttons. The parent is ConfirmPrompt, which makes one choice. Buying pieces separately is the first draft, where each part is chosen on its own. Moving school is the app running on Windows, and a new school is a new family class.