Factory Method Pattern

The Factory Method pattern: letting subclasses decide which class of object to create, so the code that uses the object never names it.

  • 9 cards
  • 4 questions
  • About 16 min
  • Intermediate to Advanced
Share

Code that calls a constructor is tied to the class it names. The Factory Method pattern loosens that tie: a base class writes everything that uses the object, and leaves one method, the factory method, for each subclass to override with the class it wants created.

This topic starts with the problem and the intent, then reads the pattern's four participants off its class diagram and builds the pure form in Python, Java and TypeScript. Two examples follow, one written for an application, a notifier that sends by email or SMS, and one met in a library, Java's Collection.iterator(), so that the same roles can be seen in code you did not write.

In Python a class can be passed around like any value, and one card shows how far that replaces the subclass. The gotcha is the factory method with nothing to choose between, and the exercise is the Gang of Four's own case, an editor that opens more than one kind of document.

By the end you can recognise a factory method from its shape, name each participant in a real case, and judge whether one is earning its place.

Contents

9 cardsnot started