Simple Factory: One Place That Says new

When the same if chain that picks a class is copied into several places, a new product means editing all of them, and one is always forgotten; a simple factory moves that decision into one function, so a new product is one new class and one new line.

Apprentice · OOP · Updated

By

After this lesson you can

  • Move every new for a family of products into one factory, so a new product is one new class and one new line
  • Spot the smells that point to a factory: the same if chain that picks a class, copied into several places

Key takeaways

  • The smell: the same if chain that turns a name into an object, copied into more than one place.
  • The cause: the decision "which class for this name?" has no home of its own, so every caller makes it again.
  • The fix: one function (or class) is the only place that says new for those products. Everyone else asks it.
  • Teams found this so often that it has a name, the simple factory; it's the plainest of the factory patterns.

Before this: Meet the Bakery App, which builds the app this lesson changes, and interfaces (a promise any class can keep).

Sunrise Bakery's owner has news: pies launch next month, at $15. In version 1 that's one more else if in takeOrder. But version 1 has grown since then. The counter tablet also shows a price board, the list of everything for sale with its price, and the price board turns words into products too. So does the kitchen's ticket printer. Every place that needs a product says new Cake() itself. By the end of this lesson you'll have met the first and plainest of the factory patterns, the simple factory; first, the problem it grew out of.

The symptom: the same if chain, twice

Here is the app with pies added. The new Pie class is there, and takeOrder knows about it. The price board's code was written by someone else last spring:

List<IProduct> order = TakeOrder(new List<string> { "pie", "cake" });
List<string> board = PriceBoard(new List<string> { "cake", "cupcakes", "cookies", "pie" });
Console.WriteLine("Order: " + string.Join(", ", order.Select(product => product.Name)));
Console.WriteLine("Price board: " + string.Join(", ", board));

List<IProduct> TakeOrder(List<string> kinds)
{
    List<IProduct> products = new List<IProduct>();
    foreach (string kind in kinds)
    {
        if (kind == "cake") { products.Add(new Cake()); }
        else if (kind == "cupcakes") { products.Add(new Cupcakes()); }
        else if (kind == "cookies") { products.Add(new CookieBox()); }
        else if (kind == "pie") { products.Add(new Pie()); }
    }
    return products;
}

List<string> PriceBoard(List<string> kinds)
{
    List<string> lines = new List<string>();
    foreach (string kind in kinds)
    {
        IProduct? product = null;
        if (kind == "cake") { product = new Cake(); }
        else if (kind == "cupcakes") { product = new Cupcakes(); }
        else if (kind == "cookies") { product = new CookieBox(); }
        if (product != null)
        {
            lines.Add(quot;{product.Name}: ${product.Price}");
        }
    }
    return lines;
}

interface IProduct
{
    string Name { get; }
    int Price { get; }
}

class Cake : IProduct { public string Name => "Cake"; public int Price => 30; }
class Cupcakes : IProduct { public string Name => "Cupcakes"; public int Price => 12; }
class CookieBox : IProduct { public string Name => "Cookie box"; public int Price => 8; }
class Pie : IProduct { public string Name => "Pie"; public int Price => 15; }
Order: Pie, Cake
Price board: Cake: $30, Cupcakes: $12, Cookie box: $8
interface Product {
    String name();
    int price();
}

class Cake implements Product { public String name() { return "Cake"; } public int price() { return 30; } }
class Cupcakes implements Product { public String name() { return "Cupcakes"; } public int price() { return 12; } }
class CookieBox implements Product { public String name() { return "Cookie box"; } public int price() { return 8; } }
class Pie implements Product { public String name() { return "Pie"; } public int price() { return 15; } }

List<Product> takeOrder(List<String> kinds) {
    List<Product> products = new ArrayList<>();
    for (String kind : kinds) {
        if (kind.equals("cake")) { products.add(new Cake()); }
        else if (kind.equals("cupcakes")) { products.add(new Cupcakes()); }
        else if (kind.equals("cookies")) { products.add(new CookieBox()); }
        else if (kind.equals("pie")) { products.add(new Pie()); }
    }
    return products;
}

List<String> priceBoard(List<String> kinds) {
    List<String> lines = new ArrayList<>();
    for (String kind : kinds) {
        Product product = null;
        if (kind.equals("cake")) { product = new Cake(); }
        else if (kind.equals("cupcakes")) { product = new Cupcakes(); }
        else if (kind.equals("cookies")) { product = new CookieBox(); }
        if (product != null) {
            lines.add(product.name() + ": quot; + product.price());
        }
    }
    return lines;
}

void main() {
    List<Product> order = takeOrder(List.of("pie", "cake"));
    List<String> board = priceBoard(List.of("cake", "cupcakes", "cookies", "pie"));
    IO.println("Order: " + String.join(", ", order.stream().map(Product::name).toList()));
    IO.println("Price board: " + String.join(", ", board));
}
Order: Pie, Cake
Price board: Cake: $30, Cupcakes: $12, Cookie box: $8
class Cake:
    name = "Cake"
    price = 30


class Cupcakes:
    name = "Cupcakes"
    price = 12


class CookieBox:
    name = "Cookie box"
    price = 8


class Pie:
    name = "Pie"
    price = 15


def take_order(kinds):
    products = []
    for kind in kinds:
        if kind == "cake":
            products.append(Cake())
        elif kind == "cupcakes":
            products.append(Cupcakes())
        elif kind == "cookies":
            products.append(CookieBox())
        elif kind == "pie":
            products.append(Pie())
    return products


def price_board(kinds):
    lines = []
    for kind in kinds:
        product = None
        if kind == "cake":
            product = Cake()
        elif kind == "cupcakes":
            product = Cupcakes()
        elif kind == "cookies":
            product = CookieBox()
        if product is not None:
            lines.append(f"{product.name}: ${product.price}")
    return lines


order = take_order(["pie", "cake"])
board = price_board(["cake", "cupcakes", "cookies", "pie"])
print("Order: " + ", ".join(product.name for product in order))
print("Price board: " + ", ".join(board))
Order: Pie, Cake
Price board: Cake: $30, Cupcakes: $12, Cookie box: $8
class Cake { name = "Cake"; price = 30; }
class Cupcakes { name = "Cupcakes"; price = 12; }
class CookieBox { name = "Cookie box"; price = 8; }
class Pie { name = "Pie"; price = 15; }

function takeOrder(kinds) {
  const products = [];
  for (const kind of kinds) {
    if (kind === "cake") { products.push(new Cake()); }
    else if (kind === "cupcakes") { products.push(new Cupcakes()); }
    else if (kind === "cookies") { products.push(new CookieBox()); }
    else if (kind === "pie") { products.push(new Pie()); }
  }
  return products;
}

function priceBoard(kinds) {
  const lines = [];
  for (const kind of kinds) {
    let product = null;
    if (kind === "cake") { product = new Cake(); }
    else if (kind === "cupcakes") { product = new Cupcakes(); }
    else if (kind === "cookies") { product = new CookieBox(); }
    if (product !== null) {
      lines.push(`${product.name}: ${product.price}`);
    }
  }
  return lines;
}

const order = takeOrder(["pie", "cake"]);
const board = priceBoard(["cake", "cupcakes", "cookies", "pie"]);
console.log("Order: " + order.map((product) => product.name).join(", "));
console.log("Price board: " + board.join(", "));
Order: Pie, Cake
Price board: Cake: $30, Cupcakes: $12, Cookie box: $8
interface Product {
  name: string;
  price: number;
}

class Cake implements Product { name = "Cake"; price = 30; }
class Cupcakes implements Product { name = "Cupcakes"; price = 12; }
class CookieBox implements Product { name = "Cookie box"; price = 8; }
class Pie implements Product { name = "Pie"; price = 15; }

function takeOrder(kinds: string[]): Product[] {
  const products: Product[] = [];
  for (const kind of kinds) {
    if (kind === "cake") { products.push(new Cake()); }
    else if (kind === "cupcakes") { products.push(new Cupcakes()); }
    else if (kind === "cookies") { products.push(new CookieBox()); }
    else if (kind === "pie") { products.push(new Pie()); }
  }
  return products;
}

function priceBoard(kinds: string[]): string[] {
  const lines: string[] = [];
  for (const kind of kinds) {
    let product: Product | null = null;
    if (kind === "cake") { product = new Cake(); }
    else if (kind === "cupcakes") { product = new Cupcakes(); }
    else if (kind === "cookies") { product = new CookieBox(); }
    if (product !== null) {
      lines.push(`${product.name}: ${product.price}`);
    }
  }
  return lines;
}

const order = takeOrder(["pie", "cake"]);
const board = priceBoard(["cake", "cupcakes", "cookies", "pie"]);
console.log("Order: " + order.map((product) => product.name).join(", "));
console.log("Price board: " + board.join(", "));
Order: Pie, Cake
Price board: Cake: $30, Cupcakes: $12, Cookie box: $8

Customers can order a pie, but the price board doesn't show one. Nobody broke anything on purpose: the person adding pies found one if chain and didn't know about the other. With the kitchen printer, there are three.

That's a code smell: something in the code that hints at a deeper problem, the way a cough hints at a cold. Read it as a doctor would:

  • The symptom: the same if chain, turning a word into an object, copied into several places.
  • The cause: the decision "which class goes with this word?" has no home. Every caller makes it again, so every caller has to change together.
  • The cure: coming up, once we've tried the obvious fixes.

What would you try?

Add else if (kind == "pie") everywhere. It works, today. But "everywhere" is the problem: nothing tells you where everywhere is, and next month's product needs the same hunt.

Put a comment on each chain: "keep this in step with the others". A comment can't make anyone read it, and it doesn't stop the copies from growing.

Make one big Product class with a kind field, and if checks inside it for the price. Now one class holds every product's rules. It fixes the copying, but every new product edits that one class, and it grows forever.

What we actually want is for the question "which class goes with this word?" to be answered in exactly one place.

The fix: one place that says new

A rental-car counter works this way. You don't walk onto the lot and pick a car by its model. You ask for "a midsize", and the counter hands you the keys. Only the counter knows which cars are midsize this week.

A rental-car counter: a customer says "a midsize, please" and the clerk hands over car keys, while behind the clerk a board of key hooks is labeled Compact, Midsize and SUV

In code, the counter is one function that takes the word and hands back the product. It's the only code in the app that says new Cake(). Everyone else asks it:

A role diagram: takeOrder and the price board each ask for a product by name from one place that says new (makeProduct), which makes Cake, Cupcakes, Cookie box and the new Pie, all inside a dashed fence labeled "what changes: the products"

List<IProduct> order = TakeOrder(new List<string> { "pie", "cake" });
List<string> board = PriceBoard(new List<string> { "cake", "cupcakes", "cookies", "pie" });
Console.WriteLine("Order: " + string.Join(", ", order.Select(product => product.Name)));
Console.WriteLine("Price board: " + string.Join(", ", board));

// The one place that says new for a product.
IProduct MakeProduct(string kind)
{
    if (kind == "cake") { return new Cake(); }
    if (kind == "cupcakes") { return new Cupcakes(); }
    if (kind == "cookies") { return new CookieBox(); }
    if (kind == "pie") { return new Pie(); }
    throw new ArgumentException("No such product: " + kind);
}

List<IProduct> TakeOrder(List<string> kinds)
{
    List<IProduct> products = new List<IProduct>();
    foreach (string kind in kinds)
    {
        products.Add(MakeProduct(kind));
    }
    return products;
}

List<string> PriceBoard(List<string> kinds)
{
    List<string> lines = new List<string>();
    foreach (string kind in kinds)
    {
        IProduct product = MakeProduct(kind);
        lines.Add(quot;{product.Name}: ${product.Price}");
    }
    return lines;
}

interface IProduct
{
    string Name { get; }
    int Price { get; }
}

class Cake : IProduct { public string Name => "Cake"; public int Price => 30; }
class Cupcakes : IProduct { public string Name => "Cupcakes"; public int Price => 12; }
class CookieBox : IProduct { public string Name => "Cookie box"; public int Price => 8; }
class Pie : IProduct { public string Name => "Pie"; public int Price => 15; }
Order: Pie, Cake
Price board: Cake: $30, Cupcakes: $12, Cookie box: $8, Pie: $15
interface Product {
    String name();
    int price();
}

class Cake implements Product { public String name() { return "Cake"; } public int price() { return 30; } }
class Cupcakes implements Product { public String name() { return "Cupcakes"; } public int price() { return 12; } }
class CookieBox implements Product { public String name() { return "Cookie box"; } public int price() { return 8; } }
class Pie implements Product { public String name() { return "Pie"; } public int price() { return 15; } }

// The one place that says new for a product.
Product makeProduct(String kind) {
    if (kind.equals("cake")) { return new Cake(); }
    if (kind.equals("cupcakes")) { return new Cupcakes(); }
    if (kind.equals("cookies")) { return new CookieBox(); }
    if (kind.equals("pie")) { return new Pie(); }
    throw new IllegalArgumentException("No such product: " + kind);
}

List<Product> takeOrder(List<String> kinds) {
    List<Product> products = new ArrayList<>();
    for (String kind : kinds) {
        products.add(makeProduct(kind));
    }
    return products;
}

List<String> priceBoard(List<String> kinds) {
    List<String> lines = new ArrayList<>();
    for (String kind : kinds) {
        Product product = makeProduct(kind);
        lines.add(product.name() + ": quot; + product.price());
    }
    return lines;
}

void main() {
    List<Product> order = takeOrder(List.of("pie", "cake"));
    List<String> board = priceBoard(List.of("cake", "cupcakes", "cookies", "pie"));
    IO.println("Order: " + String.join(", ", order.stream().map(Product::name).toList()));
    IO.println("Price board: " + String.join(", ", board));
}
Order: Pie, Cake
Price board: Cake: $30, Cupcakes: $12, Cookie box: $8, Pie: $15
class Cake:
    name = "Cake"
    price = 30


class Cupcakes:
    name = "Cupcakes"
    price = 12


class CookieBox:
    name = "Cookie box"
    price = 8


class Pie:
    name = "Pie"
    price = 15


def make_product(kind):
    """The one place that says new for a product."""
    if kind == "cake":
        return Cake()
    if kind == "cupcakes":
        return Cupcakes()
    if kind == "cookies":
        return CookieBox()
    if kind == "pie":
        return Pie()
    raise ValueError(f"No such product: {kind}")


def take_order(kinds):
    return [make_product(kind) for kind in kinds]


def price_board(kinds):
    lines = []
    for kind in kinds:
        product = make_product(kind)
        lines.append(f"{product.name}: ${product.price}")
    return lines


order = take_order(["pie", "cake"])
board = price_board(["cake", "cupcakes", "cookies", "pie"])
print("Order: " + ", ".join(product.name for product in order))
print("Price board: " + ", ".join(board))
Order: Pie, Cake
Price board: Cake: $30, Cupcakes: $12, Cookie box: $8, Pie: $15
class Cake { name = "Cake"; price = 30; }
class Cupcakes { name = "Cupcakes"; price = 12; }
class CookieBox { name = "Cookie box"; price = 8; }
class Pie { name = "Pie"; price = 15; }

// The one place that says new for a product.
function makeProduct(kind) {
  if (kind === "cake") { return new Cake(); }
  if (kind === "cupcakes") { return new Cupcakes(); }
  if (kind === "cookies") { return new CookieBox(); }
  if (kind === "pie") { return new Pie(); }
  throw new Error(`No such product: ${kind}`);
}

function takeOrder(kinds) {
  return kinds.map((kind) => makeProduct(kind));
}

function priceBoard(kinds) {
  return kinds.map((kind) => {
    const product = makeProduct(kind);
    return `${product.name}: ${product.price}`;
  });
}

const order = takeOrder(["pie", "cake"]);
const board = priceBoard(["cake", "cupcakes", "cookies", "pie"]);
console.log("Order: " + order.map((product) => product.name).join(", "));
console.log("Price board: " + board.join(", "));
Order: Pie, Cake
Price board: Cake: $30, Cupcakes: $12, Cookie box: $8, Pie: $15
interface Product {
  name: string;
  price: number;
}

class Cake implements Product { name = "Cake"; price = 30; }
class Cupcakes implements Product { name = "Cupcakes"; price = 12; }
class CookieBox implements Product { name = "Cookie box"; price = 8; }
class Pie implements Product { name = "Pie"; price = 15; }

// The one place that says new for a product.
function makeProduct(kind: string): Product {
  if (kind === "cake") { return new Cake(); }
  if (kind === "cupcakes") { return new Cupcakes(); }
  if (kind === "cookies") { return new CookieBox(); }
  if (kind === "pie") { return new Pie(); }
  throw new Error(`No such product: ${kind}`);
}

function takeOrder(kinds: string[]): Product[] {
  return kinds.map((kind) => makeProduct(kind));
}

function priceBoard(kinds: string[]): string[] {
  return kinds.map((kind) => {
    const product = makeProduct(kind);
    return `${product.name}: ${product.price}`;
  });
}

const order = takeOrder(["pie", "cake"]);
const board = priceBoard(["cake", "cupcakes", "cookies", "pie"]);
console.log("Order: " + order.map((product) => product.name).join(", "));
console.log("Price board: " + board.join(", "));
Order: Pie, Cake
Price board: Cake: $30, Cupcakes: $12, Cookie box: $8, Pie: $15

The pie is on the board now, and nobody went looking for it. takeOrder and the price board no longer know any product's class. They only know there's a function that makes products. Next month's product is one new class and one new line in makeProduct, and every screen gets it at once.

A word the app doesn't know, such as "bagel", now stops with a clear message instead of quietly vanishing from one screen and not the other.

How it got its name

This fix is so common that it has a name: a simple factory, the plain version of the factory pattern. It's "a factory" because it makes things, and "simple" because it's one function with one decision in it. You'll often see it written as a class, a ProductFactory with a Create method; that's the same idea in a box. The original 1994 book of patterns doesn't list it: it's where the book's two factory patterns (which you'll meet in Pass 2 and Pass 3) start.

Where you've already used it

  • document.createElement("button") in a browser takes the word "button" and hands back the right kind of element object. You never write new HTMLButtonElement().
  • Python's open("menu.txt") hands back a text-file object, and open("logo.png", "rb") an object of a different class for raw bytes. You never pick the class.
  • C#'s Encoding.GetEncoding("utf-8") and Java's Calendar.getInstance() decide which class to give you, so your code doesn't have to.

When not to use it

  • When there's only one place that makes the object. A factory for a single caller is an extra jump for the reader and no help to anyone.
  • When the kinds will never change. Two kinds that are fixed for good, such as "dine in" or "take out", read fine as a plain if.

The cost is small: one more function to look at. The test is simple too: if the same "which class?" decision appears in two places, give it one home.

How often you'll meet it: every day (our estimate: it depends on the language and the kind of work, but almost every app turns words or codes into objects somewhere).

Check yourself

2 questions to try on the lesson page.

So what

When you see the same if chain picking a class in two places, you've found the first smell of this course and its cure. A new product is now one new class and one new line, and the next lesson makes even that line simpler.

Key terms

Cheat sheets