Skip to the guide

Factory method and simple factory

BeginnerPattern7 pages

A factory is code whose only job is to make objects, so the code that uses them never chooses their class. The everyday version, a simple factory, turns a name into the right object, and it is not one of the 23 patterns in the 1994 book, Design Patterns. The book's Factory Method has a different shape, with the intent to "define an interface for creating an object, but let subclasses decide which class to instantiate." Interviewers listen for where you put creation, and for whether you know when a constructor call is enough.

A paint-mixing counter

Think of the paint counter at a hardware shop. A customer hands over a colour code, and the mixing machine behind the counter looks up the code in its recipe book. Then it mixes a fresh tin for that customer, since a tin mixed for the last customer is already sold. The painters who use the paint never see the recipe. A new colour is one new recipe card in the machine, and a code the machine doesn't know is refused, never mixed as plain white.

Before the shop bought the machine, every painter carried his own recipe cards and mixed his own paint. A new colour then meant a new card in every painter's pocket.