Programming Search⌘K

Patternintro

Simple factory

Also called simple factory pattern, factory function, parameterized factory, static factory with a switch.

A simple factory is one function that takes a parameter, picks a concrete class from it and returns a new object. Callers use the object through an interface and do not name the class.

Family
creational-design
Intent
Put the choice of a concrete class in one function, which takes a parameter and returns a new object through a common interface, so that callers do not create the concrete classes themselves.
Also called
Factory, Factory function

Intent

Put the choice of a concrete class in one function. The function takes a parameter, picks a class from it, and returns a new object. The callers use the object through a common interface, so they do not need to know the concrete classes.1

Problem

A shop sends a message to a user when an order ships. The user chooses the channel: email, SMS or a push message to the app. Each channel has its own class, and all of them have a send method.

The code that sends the message must create an object of the right class. If each caller does this with its own if statement, the same conditional is in many places. When the shop adds a channel, each copy must change, and a copy that is not changed fails at run time. The forces are these:

  • The concrete class depends on a value that is known only at run time, such as a setting or an input.
  • Many callers need such an object, and they need only its interface.
  • A constructor cannot make this choice. A constructor creates an object of its own class, and when it runs there is no object yet to dispatch on.2

Solution

Write one function, the simple factory, that takes the parameter and returns the object. The function holds the only conditional that names the concrete classes. Refactoring.Guru describes it as one creation method with a large conditional that, based on the parameters, chooses which product class to instantiate and then returns it.1

 Client                       make_notifier(channel)             products
 ------                       ----------------------             --------
 n = make_notifier("sms") --> "email"? -> new EmailNotifier       EmailNotifier
                              "sms"?   -> new SmsNotifier  -----> SmsNotifier
                              "push"?  -> new PushNotifier        PushNotifier
                              else     -> error
 n.send(user, text)  ------------------------------------------> SmsNotifier.send

The participants are the factory, the product interface, and the concrete products. The factory can be a free function, a static method or a method of a small factory object. In a language where classes are values, such as Python or JavaScript, a table from the parameter to the class can replace the conditional.

Not a GoF pattern. Design Patterns has no pattern named "factory". It has two patterns that use factories, Factory Method and Abstract Factory. Some sources call the general idea the factory pattern, and others consider it a programming idiom and call it a simple factory.2 The name comes from Head First Design Patterns.13

Example

The example files show one simple factory in each language. make_notifier takes a channel name and returns an email, SMS or push notifier. The program asks for each of the three channels and for an unknown channel, fax, which gives an error:

Language Factory Unknown channel
Python a function with an if chain ValueError
JavaScript a Map from the name to the class RangeError
TypeScript a switch on a union type, with a never check rejected by a type guard
Java a switch expression IllegalArgumentException
C# a switch expression ArgumentException
C++ a function that returns std::unique_ptr<Notifier> std::invalid_argument
Go NewNotifier returns an interface and an error an error value
Rust a match that returns Box<dyn Notifier> Err
PythonGitHub
from typing import Protocol


class Notifier(Protocol):
    def send(self, user: str, text: str) -> str: ...


class EmailNotifier:
    def send(self, user: str, text: str) -> str:
        return f"mail to {user}@example.com: {text}"


class SmsNotifier:
    def send(self, user: str, text: str) -> str:
        return f"text to the phone of {user}: {text}"


class PushNotifier:
    def send(self, user: str, text: str) -> str:
        return f"push to the app of {user}: {text}"


def make_notifier(channel: str) -> Notifier:
    """The one place that knows the concrete classes."""
    if channel == "email":
        return EmailNotifier()
    if channel == "sms":
        return SmsNotifier()
    if channel == "push":
        return PushNotifier()
    raise ValueError(f"unknown channel: {channel}")


for channel in ["email", "sms", "push", "fax"]:
    try:
        notifier = make_notifier(channel)
    except ValueError as e:
        print(e)
        continue
    print(f"{type(notifier).__name__}: {notifier.send('ann', 'order shipped')}")
Output
EmailNotifier: mail to ann@example.com: order shipped
SmsNotifier: text to the phone of ann: order shipped
PushNotifier: push to the app of ann: order shipped
unknown channel: fax
  • Verdict: idiom. A module-level function is the simple factory. The caller sees only the Notifier protocol.
  • A dict from the parameter to the class, such as {"email": EmailNotifier, "sms": SmsNotifier}, replaces the if chain. Classes are callable objects in Python, so the factory calls the class it finds.
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>

struct Notifier {
    virtual ~Notifier() = default;
    virtual std::string name() const = 0;
    virtual std::string send(const std::string& user, const std::string& text) const = 0;
};

struct EmailNotifier : Notifier {
    std::string name() const override { return "EmailNotifier"; }
    std::string send(const std::string& user, const std::string& text) const override {
        return "mail to " + user + "@example.com: " + text;
    }
};

struct SmsNotifier : Notifier {
    std::string name() const override { return "SmsNotifier"; }
    std::string send(const std::string& user, const std::string& text) const override {
        return "text to the phone of " + user + ": " + text;
    }
};

struct PushNotifier : Notifier {
    std::string name() const override { return "PushNotifier"; }
    std::string send(const std::string& user, const std::string& text) const override {
        return "push to the app of " + user + ": " + text;
    }
};

// The one place that knows the concrete classes.
std::unique_ptr<Notifier> make_notifier(const std::string& channel) {
    if (channel == "email") return std::make_unique<EmailNotifier>();
    if (channel == "sms") return std::make_unique<SmsNotifier>();
    if (channel == "push") return std::make_unique<PushNotifier>();
    throw std::invalid_argument("unknown channel: " + channel);
}

int main() {
    for (const std::string channel : {"email", "sms", "push", "fax"}) {
        std::unique_ptr<Notifier> notifier;
        try {
            notifier = make_notifier(channel);
        } catch (const std::invalid_argument& e) {
            std::cout << e.what() << "\n";
            continue;
        }
        std::cout << notifier->name() << ": " << notifier->send("ann", "order shipped") << "\n";
    }
}
Output
EmailNotifier: mail to ann@example.com: order shipped
SmsNotifier: text to the phone of ann: order shipped
PushNotifier: push to the app of ann: order shipped
unknown channel: fax
  • Verdict: idiom. A free function returns std::unique_ptr to the base class. The caller owns the object, and only the file with the factory needs the headers of the concrete classes.
  • The base class needs a virtual destructor, so that deleting through the base pointer runs the destructor of the concrete class.
JavaGitHub
import java.util.List;

public class Main {
    interface Notifier {
        String send(String user, String text);
    }

    static final class EmailNotifier implements Notifier {
        public String send(String user, String text) {
            return "mail to " + user + "@example.com: " + text;
        }
    }

    static final class SmsNotifier implements Notifier {
        public String send(String user, String text) {
            return "text to the phone of " + user + ": " + text;
        }
    }

    static final class PushNotifier implements Notifier {
        public String send(String user, String text) {
            return "push to the app of " + user + ": " + text;
        }
    }

    /** The one place that knows the concrete classes. */
    static Notifier makeNotifier(String channel) {
        return switch (channel) {
            case "email" -> new EmailNotifier();
            case "sms" -> new SmsNotifier();
            case "push" -> new PushNotifier();
            default -> throw new IllegalArgumentException("unknown channel: " + channel);
        };
    }

    public static void main(String[] args) {
        for (String channel : List.of("email", "sms", "push", "fax")) {
            Notifier notifier;
            try {
                notifier = makeNotifier(channel);
            } catch (IllegalArgumentException e) {
                System.out.println(e.getMessage());
                continue;
            }
            System.out.println(notifier.getClass().getSimpleName() + ": "
                    + notifier.send("ann", "order shipped"));
        }
    }
}
Output
EmailNotifier: mail to ann@example.com: order shipped
SmsNotifier: text to the phone of ann: order shipped
PushNotifier: push to the app of ann: order shipped
unknown channel: fax
  • Verdict: idiom. A static method with a switch expression is the simple factory. The return type is the interface, so callers do not depend on the concrete classes.
  • With an enum for the channel in place of a String, a switch expression that covers every constant needs no default branch, and the compiler reports a missing constant.
using System;

foreach (var channel in new[] { "email", "sms", "push", "fax" })
{
    INotifier notifier;
    try
    {
        notifier = NotifierFactory.Make(channel);
    }
    catch (ArgumentException e)
    {
        Console.WriteLine(e.Message);
        continue;
    }
    Console.WriteLine($"{notifier.GetType().Name}: {notifier.Send("ann", "order shipped")}");
}

interface INotifier
{
    string Send(string user, string text);
}

sealed class EmailNotifier : INotifier
{
    public string Send(string user, string text) => $"mail to {user}@example.com: {text}";
}

sealed class SmsNotifier : INotifier
{
    public string Send(string user, string text) => $"text to the phone of {user}: {text}";
}

sealed class PushNotifier : INotifier
{
    public string Send(string user, string text) => $"push to the app of {user}: {text}";
}

static class NotifierFactory
{
    // The one place that knows the concrete classes.
    public static INotifier Make(string channel) => channel switch
    {
        "email" => new EmailNotifier(),
        "sms" => new SmsNotifier(),
        "push" => new PushNotifier(),
        _ => throw new ArgumentException($"unknown channel: {channel}"),
    };
}
Output
EmailNotifier: mail to ann@example.com: order shipped
SmsNotifier: text to the phone of ann: order shipped
PushNotifier: push to the app of ann: order shipped
unknown channel: fax
  • Verdict: idiom. A static class with a switch expression is the simple factory, and the return type is the interface.
  • In an application that uses a dependency injection container, the container can take this role: it maps an interface to a class from configuration.
JavaScriptGitHub
class EmailNotifier {
  send(user, text) {
    return `mail to ${user}@example.com: ${text}`;
  }
}

class SmsNotifier {
  send(user, text) {
    return `text to the phone of ${user}: ${text}`;
  }
}

class PushNotifier {
  send(user, text) {
    return `push to the app of ${user}: ${text}`;
  }
}

// The one place that knows the concrete classes.
const NOTIFIERS = new Map([
  ["email", EmailNotifier],
  ["sms", SmsNotifier],
  ["push", PushNotifier],
]);

function makeNotifier(channel) {
  const Kind = NOTIFIERS.get(channel);
  if (Kind === undefined) throw new RangeError(`unknown channel: ${channel}`);
  return new Kind();
}

for (const channel of ["email", "sms", "push", "fax"]) {
  let notifier;
  try {
    notifier = makeNotifier(channel);
  } catch (e) {
    console.log(e.message);
    continue;
  }
  console.log(`${notifier.constructor.name}: ${notifier.send("ann", "order shipped")}`);
}
Output
EmailNotifier: mail to ann@example.com: order shipped
SmsNotifier: text to the phone of ann: order shipped
PushNotifier: push to the app of ann: order shipped
unknown channel: fax
  • Verdict: idiom. A class is a value in JavaScript, so a Map from the parameter to the class replaces a switch.
  • A Map is safer than a plain object for the table, because a lookup in a plain object also finds inherited keys such as "toString".
TypeScriptGitHub
interface Notifier {
  send(user: string, text: string): string;
}

class EmailNotifier implements Notifier {
  send(user: string, text: string): string {
    return `mail to ${user}@example.com: ${text}`;
  }
}

class SmsNotifier implements Notifier {
  send(user: string, text: string): string {
    return `text to the phone of ${user}: ${text}`;
  }
}

class PushNotifier implements Notifier {
  send(user: string, text: string): string {
    return `push to the app of ${user}: ${text}`;
  }
}

type Channel = "email" | "sms" | "push";

// The one place that knows the concrete classes.
function makeNotifier(channel: Channel): Notifier {
  switch (channel) {
    case "email":
      return new EmailNotifier();
    case "sms":
      return new SmsNotifier();
    case "push":
      return new PushNotifier();
    default: {
      const unknown: never = channel; // a compile error if a case is missing
      throw new RangeError(`unknown channel: ${String(unknown)}`);
    }
  }
}

function isChannel(text: string): text is Channel {
  return text === "email" || text === "sms" || text === "push";
}

for (const channel of ["email", "sms", "push", "fax"]) {
  if (!isChannel(channel)) {
    console.log(`unknown channel: ${channel}`);
    continue;
  }
  const notifier = makeNotifier(channel);
  console.log(`${notifier.constructor.name}: ${notifier.send("ann", "order shipped")}`);
}
Output
EmailNotifier: mail to ann@example.com: order shipped
SmsNotifier: text to the phone of ann: order shipped
PushNotifier: push to the app of ann: order shipped
unknown channel: fax
  • Verdict: idiom. A union type for the parameter and a never check in the default branch make the compiler report a channel that the factory does not handle.
  • Text from outside, such as a configuration value, goes through a type guard before it reaches the factory.
package main

import "fmt"

type Notifier interface {
	Send(user, text string) string
}

type EmailNotifier struct{}

func (EmailNotifier) Send(user, text string) string {
	return fmt.Sprintf("mail to %s@example.com: %s", user, text)
}

type SmsNotifier struct{}

func (SmsNotifier) Send(user, text string) string {
	return fmt.Sprintf("text to the phone of %s: %s", user, text)
}

type PushNotifier struct{}

func (PushNotifier) Send(user, text string) string {
	return fmt.Sprintf("push to the app of %s: %s", user, text)
}

// NewNotifier is the one place that knows the concrete types.
func NewNotifier(channel string) (Notifier, error) {
	switch channel {
	case "email":
		return EmailNotifier{}, nil
	case "sms":
		return SmsNotifier{}, nil
	case "push":
		return PushNotifier{}, nil
	}
	return nil, fmt.Errorf("unknown channel: %s", channel)
}

func main() {
	for _, channel := range []string{"email", "sms", "push", "fax"} {
		n, err := NewNotifier(channel)
		if err != nil {
			fmt.Println(err)
			continue
		}
		fmt.Printf("%T: %s\n", n, n.Send("ann", "order shipped"))
	}
}
Output
main.EmailNotifier: mail to ann@example.com: order shipped
main.SmsNotifier: text to the phone of ann: order shipped
main.PushNotifier: push to the app of ann: order shipped
unknown channel: fax
  • Verdict: idiom. A function named New... that returns an interface and an error is the Go form. The %T verb prints the dynamic type, with its package name.
  • The function returns an interface, not a concrete type, because the concrete type depends on the argument.
RustGitHub
trait Notifier {
    fn name(&self) -> &'static str;
    fn send(&self, user: &str, text: &str) -> String;
}

struct EmailNotifier;
struct SmsNotifier;
struct PushNotifier;

impl Notifier for EmailNotifier {
    fn name(&self) -> &'static str { "EmailNotifier" }
    fn send(&self, user: &str, text: &str) -> String {
        format!("mail to {user}@example.com: {text}")
    }
}

impl Notifier for SmsNotifier {
    fn name(&self) -> &'static str { "SmsNotifier" }
    fn send(&self, user: &str, text: &str) -> String {
        format!("text to the phone of {user}: {text}")
    }
}

impl Notifier for PushNotifier {
    fn name(&self) -> &'static str { "PushNotifier" }
    fn send(&self, user: &str, text: &str) -> String {
        format!("push to the app of {user}: {text}")
    }
}

// The one place that knows the concrete types.
fn make_notifier(channel: &str) -> Result<Box<dyn Notifier>, String> {
    match channel {
        "email" => Ok(Box::new(EmailNotifier)),
        "sms" => Ok(Box::new(SmsNotifier)),
        "push" => Ok(Box::new(PushNotifier)),
        _ => Err(format!("unknown channel: {channel}")),
    }
}

fn main() {
    for channel in ["email", "sms", "push", "fax"] {
        match make_notifier(channel) {
            Ok(n) => println!("{}: {}", n.name(), n.send("ann", "order shipped")),
            Err(e) => println!("{e}"),
        }
    }
}
Output
EmailNotifier: mail to ann@example.com: order shipped
SmsNotifier: text to the phone of ann: order shipped
PushNotifier: push to the app of ann: order shipped
unknown channel: fax
  • Verdict: idiom. A function returns Box<dyn Notifier>, a trait object, because the concrete type is chosen at run time. An unknown parameter is an Err.
  • When the set of kinds is closed, an enum with one variant per kind and a match in each method is the alternative. It needs no heap allocation and no trait object.

Consequences

The benefits:

  • One place to change. To add a channel, add a class and one case in the factory. Wikipedia notes that a change of the factory is typically one line in one file, and that it is easier than to change every place in the code where a new object is created.2
  • Callers know only the interface. The client code deals only with the abstract type, and does not need the header files or the declarations of the concrete classes.2
  • Validation in one place. The factory decides what an unknown parameter means: an error, a default, or a null object.

The costs:

  • The factory knows every class. Each new kind changes the factory. A factory that a library ships cannot be extended by its users without a change to the library.
  • The conditional grows. Refactoring.Guru notes that the method can become too big over time. If you then move parts of it to subclasses, the result becomes the Factory Method pattern.1

The conditional must be in the factory only. The benefit is lost when callers keep their own copy of the choice. Here the shop adds the push channel, and one of two copies is not changed:

This code runs but gives a wrong answer on purpose.

class Email:
    name = "email"


class Sms:
    name = "sms"


class Push:
    name = "push"


def welcome(channel):
    if channel == "email":
        n = Email()
    elif channel == "sms":
        n = Sms()
    elif channel == "push":  # added when push came
        n = Push()
    else:
        raise ValueError(f"unknown channel: {channel}")
    return f"welcome sent by {n.name}"


def reset_password(channel):
    if channel == "email":
        n = Email()
    elif channel == "sms":
        n = Sms()
    else:  # this copy was not changed
        raise ValueError(f"unknown channel: {channel}")
    return f"reset link sent by {n.name}"


for task in (welcome, reset_password):
    try:
        print(task("push"))
    except ValueError as e:
        print(f"{task.__name__} failed: {e}")
Output
welcome sent by push
reset_password failed: unknown channel: push

The fix is to move the conditional into one make_notifier function, and to call it from both places.

When not to use it

Do not write a factory when there is only one concrete class. A constructor call is clearer, and the factory adds a name to learn.

Do not use a simple factory when users of a library must add their own kinds. A registry that users can add to, a Factory Method pattern that subclasses override, or a factory object that the caller passes in lets new kinds come without a change to the factory.

Do not use it to hide a choice that the caller already knows. If the caller always wants an SMS notifier, it can create one, or receive one by Dependency injection.

Static factory method. A Static factory method is a static method that returns an instance of its class, often of a subclass. A simple factory is often written as one, with the parameter that picks the class.

Factory Method. In the Factory Method pattern, a creator class declares a creation method, and each subclass overrides it to create its own product. The choice moves from a conditional to the class hierarchy. A simple factory that has grown too big can become a Factory Method.1

Abstract Factory. An Abstract Factory pattern creates a family of related products through one interface. A simple factory creates one kind of product, and it is not an abstract factory even when it is declared abstract.1

Registry. A table from the parameter to a constructor, which other code can add to at start-up. The factory looks up the parameter in the table in place of a fixed conditional, so a plug-in can add a kind without a change to the factory.

Known uses

  • Python: the built-in open() returns a different class for each mode. In text mode it returns an io.TextIOWrapper. In binary mode with buffering it returns an io.BufferedReader, an io.BufferedWriter or an io.BufferedRandom, by the mode. With buffering disabled it returns an io.FileIO.4 The pure-Python version in Lib/_pyio.py at v3.14.0 shows the choice: it creates a FileIO, then wraps it in a buffered class picked by the mode, then in a TextIOWrapper unless the mode is binary.5
  • Java: Calendar.getInstance() returns a Calendar whose fields are set to the current date and time.6 The private method createCalendar in java/util/Calendar.java at jdk-25+36 picks the class from the locale: a BuddhistCalendar for the th_TH locale, a JapaneseImperialCalendar for the ja_JP_JP locale, and a GregorianCalendar for other locales.7 The caller sees only the abstract class Calendar.

References

  1. Factory Comparison, Refactoring.Guru, 4. Simple factory pattern
  2. Factory (object-oriented programming), Wikipedia, Terminology; Use; Applications
  3. Eric Freeman, Elisabeth Freeman, Kathy Sierra and Bert Bates, Head First Design Patterns, O'Reilly, 2004, Chapter 4, The Factory Pattern, The Simple Factory defined
  4. Built-in Functions, The Python Standard Library, Python 3.14, open
  5. CPython v3.14.0 source, Lib/_pyio.py, open, lines 232 to 268
  6. Calendar, Java SE 25 API, Class description; getInstance()
  7. OpenJDK jdk-25+36 source, java/util/Calendar.java, createCalendar, lines 1688 to 1732

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/DCC5WZ/text.yaml