Choosing a Creational Pattern

By now the course has made objects six ways: a simple factory, a dictionary of functions, Factory Method, Abstract Factory, Builder and Prototype. One look-alike table compares them with plain new, the honest default, so the next object you make gets the way that fits its problem, not the newest pattern you learned.

Journeyman · OOP · Updated

By

After this lesson you can

  • Choose how to make an object (plain new, a factory, a dictionary of functions, Factory Method, Abstract Factory, Builder or Prototype), and say why
  • Spot pattern fever in object creation: a factory, kit or builder where plain new would do

Key takeaways

  • Plain new is the honest default: one class, chosen once, that nothing will swap. Reach for a pattern only when a question below says yes.
  • Picked by a name at run time: a simple factory, or a dictionary of functions when the list grows. A set of parts that must match: Abstract Factory.
  • The same steps, with each subclass deciding what to create: Factory Method. Many optional settings: Builder. A copy of one you already have: Prototype.
  • A factory with one product and one caller is pattern fever: more code, more jumps, nothing gained.

Before this: Simple Factory, Factories the Modern Way and Abstract Factory. Factory Method, Builder and Prototype are taught in Pass 2; this lesson says what each one is for in a paragraph, so it stands on its own.

The morning after the kits went in, Leo, one of the HomeBase developers, opened a pull request. He'd been reading about patterns, and he'd given the hub's activity log, the list of everything the hub did today, a factory of its own. "In case we need a different log one day," he wrote. Priya, reviewing it, asked one question: "Which day?" This lesson is about that question. The course has now made objects six different ways, and every one of them is right for some problem and wrong for most.

The symptom: a pattern with nothing to do

Here is Leo's log, made the patterned way:

ILogFactory factory = new HubLogFactory();
ILog log = factory.CreateLog();
log.Add("hub started");
log.Add("kitchen light on");

interface ILog { void Add(string line); }
interface ILogFactory { ILog CreateLog(); }

class HubLog : ILog { public void Add(string line) => Console.WriteLine(quot;Log: {line}"); }
class HubLogFactory : ILogFactory { public ILog CreateLog() => new HubLog(); }
Log: hub started
Log: kitchen light on
interface Log { void add(String line); }
interface LogFactory { Log createLog(); }

class HubLog implements Log { public void add(String line) { IO.println("Log: " + line); } }
class HubLogFactory implements LogFactory { public Log createLog() { return new HubLog(); } }

void main() {
    LogFactory factory = new HubLogFactory();
    Log log = factory.createLog();
    log.add("hub started");
    log.add("kitchen light on");
}
Log: hub started
Log: kitchen light on
class HubLog:
    def add(self, line):
        print(f"Log: {line}")


class HubLogFactory:
    def create_log(self):
        return HubLog()


factory = HubLogFactory()
log = factory.create_log()
log.add("hub started")
log.add("kitchen light on")
Log: hub started
Log: kitchen light on
class HubLog { add(line) { console.log(`Log: ${line}`); } }
class HubLogFactory { createLog() { return new HubLog(); } }

const factory = new HubLogFactory();
const log = factory.createLog();
log.add("hub started");
log.add("kitchen light on");
Log: hub started
Log: kitchen light on
interface Log { add(line: string): void; }
interface LogFactory { createLog(): Log; }

class HubLog implements Log { add(line: string): void { console.log(`Log: ${line}`); } }
class HubLogFactory implements LogFactory { createLog(): Log { return new HubLog(); } }

const factory: LogFactory = new HubLogFactory();
const log: Log = factory.createLog();
log.add("hub started");
log.add("kitchen light on");
Log: hub started
Log: kitchen light on

It works. But there's one kind of log, made in one place, and nothing in the hub's plans would ever swap it. The factory and its interface add two types and a jump for the reader, and they protect against a change nobody has asked for.

  • The symptom: a factory (or a kit, or a builder) with one product and one caller.
  • The cause: reaching for the newest pattern you learned, instead of asking what problem this object has. People call it pattern fever.

Here is the same log, made plainly:

HubLog log = new HubLog();
log.Add("hub started");
log.Add("kitchen light on");

class HubLog { public void Add(string line) => Console.WriteLine(quot;Log: {line}"); }
Log: hub started
Log: kitchen light on
class HubLog { void add(String line) { IO.println("Log: " + line); } }

void main() {
    HubLog log = new HubLog();
    log.add("hub started");
    log.add("kitchen light on");
}
Log: hub started
Log: kitchen light on
class HubLog:
    def add(self, line):
        print(f"Log: {line}")


log = HubLog()
log.add("hub started")
log.add("kitchen light on")
Log: hub started
Log: kitchen light on
class HubLog { add(line) { console.log(`Log: ${line}`); } }

const log = new HubLog();
log.add("hub started");
log.add("kitchen light on");
Log: hub started
Log: kitchen light on
class HubLog { add(line: string): void { console.log(`Log: ${line}`); } }

const log = new HubLog();
log.add("hub started");
log.add("kitchen light on");
Log: hub started
Log: kitchen light on

The same two lines, with half the code. If the day ever comes when the hub needs two kinds of log, the factory is a small change to make then, with a real reason to shape it by.

What would you try?

Always use plain new. Then the bakery's six copies of the product if chain come back, and so does the Bolt reply handed to Tuneo's reader. new is the right default, not the right answer every time.

Always use a factory, to be safe. That's Leo's pull request, all over the app: every object made through a jump, and none of the jumps doing anything.

Pick the pattern that fits each object's problem. That needs a way to tell the problems apart, which is what the rest of this lesson is.

Six ways and a default

Here is every way the course has made objects, in one look-alike table:

Pattern What it's for Strengths Weaknesses Pick it when
Plain new Making one object of a class you know The shortest and clearest code; nothing to learn The class's name is written where it's used, so swapping it means editing there One class, chosen once, that nothing will swap (the honest default)
Simple Factory (Pass 1) One function that turns a name into the right object The "which class?" decision has one home The if chain grows with every new kind The same kind of thing is made from a name or setting in more than one place
Dictionary of functions (Pass 1) A map from each name to a function that makes the object A new kind is one entry, added without editing the factory The entries can end up scattered if nobody keeps them together The list of kinds is long, changes often, or is filled from outside
Factory Method (Pass 2) A base class runs the same steps and leaves one "make this object" step to each subclass The shared steps live once; each subclass decides only what differs Needs a class family (inheritance), and one subclass per kind The same routine runs for every kind, and only the object it makes differs
Abstract Factory (this chapter) One kit per family that makes every part of it The parts of one family can't be mixed with another's Adding a new kind of part means changing every kit Several parts must always come from the same family
Builder (Pass 2) Making a complicated object step by step, then building it Each setting is named; optional ones can be left out More code than a constructor; often used where named arguments would do An object has many settings, most of them optional
Prototype (Pass 2) Making a new object by copying one you already have "Same as that one, but…" is one copy and one change A shallow copy can share a list with the original by mistake The new object is mostly like an existing one

The Pass 2 rows, in a sentence each, from the package tracker:

  • Factory Method: every carrier's shipping code runs the same steps (address, label, pickup), and each carrier's subclass decides which label and pickup objects to create.
  • Builder: new Shipment(…) had nine arguments, half of them empty; a builder names each step (withInsurance(), withSignature()), then build() makes the shipment.
  • Prototype: "same as last week, new address" copies last week's shipment and changes one thing, with care that the copy gets its own list of boxes.

Questions to ask, in order

When code needs a new object, ask these in order and stop at the first yes:

  1. Is it one class, chosen once, that nothing will swap? Use plain new. Most objects stop here.
  2. Is the kind picked from a name or setting while the app runs, in more than one place? A simple factory; a dictionary of functions if the list is long or changes often.
  3. Must several parts always come from the same family? An abstract factory, one kit per family.
  4. Do several kinds run the same steps, and differ only in the object one step makes? Factory Method.
  5. Does it have many settings, most of them optional? Try your language's named and optional arguments first; a builder when the steps need checks or an order.
  6. Is it mostly a copy of one you already have? Prototype.

For HomeBase's own list:

The job First yes The fit
The activity log 1 plain new
The setup screen turns a brand typed by the installer ("bolt") into its kit 2 a dictionary from name to kit, as in Abstract Factory
A brand's connection, format and reader 3 a kit per brand
"Copy the living room's settings to the bedroom, then dim it" 6 a copy (Prototype)

Where you've already used them

  • new everywhere: new List<string>(), new ArrayList<>(), [].
  • A simple factory: document.createElement("button"), Python's open(...).
  • Abstract Factory: .NET's DbProviderFactory, which makes a matching connection and command for one database maker.
  • Builder: C#'s and Java's StringBuilder, and the many "fluent" setup calls in web frameworks (builder.Services…).
  • Prototype: JavaScript's structuredClone(settings), and Python's copy.deepcopy(settings).

When not to use any of them

Every creational pattern costs code and a jump. Leave them out when:

  • the object has one class and one place it's made;
  • you're guessing at a change nobody has asked for ("in case we need it one day");
  • the language already does the job: named arguments instead of a builder, a dictionary instead of a factory class.

How often you'll meet it: every day (our estimate: plain new is the most common way to make an object in every language; the patterns turn up where one of the questions above says yes).

Check yourself

2 questions to try on the lesson page.

So what

Start with new, and let a real problem pick the pattern: a name to turn into an object, a family that must match, a routine whose one step differs, a pile of options, or a copy. The table is the map; the questions are how you use it.

Key terms

Cheat sheets