Singleton: Only One, Ever

When two parts of an app each make their own copy of something the whole app should share, such as the shop's settings, they quietly disagree; the Singleton pattern makes a class allow only one object and gives everyone the same one.

Apprentice · OOP · Updated

By

After this lesson you can

  • Explain what the Singleton pattern promises: only one object of a class, reached from anywhere
  • Spot the smell that points to Singleton: two copies of something the whole app must share

Key takeaways

  • The smell: two copies of something there should be only one of, so a change made through one copy doesn't reach the other.
  • The cause: every part of the app says new for it, so every part gets its own.
  • The Singleton pattern hides the constructor and hands out one shared object from one place, so everyone gets the same one.
  • In Python and JavaScript, an object made once in its own module is already shared by everyone who imports it.

Before this: Meet the Bakery App, and classes with a constructor.

Sunrise Bakery charges sales tax, 8% most of the year. The tax rate and the shop's opening hours live in a settings object. The owner changes the rate on a settings screen, and checkout uses it to work out what to charge. One day the owner sets a 10% holiday rate, and checkout keeps charging 8%. The classic answer to this problem has a name you'll hear in code reviews, Singleton; first, what went wrong.

The symptom: two copies that disagree

SettingsScreen settingsScreen = new SettingsScreen();
Checkout checkout = new Checkout();
settingsScreen.SetTax(10);
Console.WriteLine(quot;Settings screen says: {settingsScreen.Settings.TaxPercent}%");
Console.WriteLine(quot;Checkout charges: ${checkout.Total(50)}");
Console.WriteLine("Same settings object? " + (ReferenceEquals(settingsScreen.Settings, checkout.Settings) ? "yes" : "no"));

class Settings
{
    public int TaxPercent { get; set; } = 8;
}

class SettingsScreen
{
    public Settings Settings { get; } = new Settings();
    public void SetTax(int percent) => Settings.TaxPercent = percent;
}

class Checkout
{
    public Settings Settings { get; } = new Settings();
    public int Total(int subtotal) => subtotal + subtotal * Settings.TaxPercent / 100;
}
Settings screen says: 10%
Checkout charges: $54
Same settings object? no
class Settings {
    int taxPercent = 8;
}

class SettingsScreen {
    Settings settings = new Settings();
    void setTax(int percent) { settings.taxPercent = percent; }
}

class Checkout {
    Settings settings = new Settings();
    int total(int subtotal) { return subtotal + subtotal * settings.taxPercent / 100; }
}

void main() {
    SettingsScreen settingsScreen = new SettingsScreen();
    Checkout checkout = new Checkout();
    settingsScreen.setTax(10);
    IO.println("Settings screen says: " + settingsScreen.settings.taxPercent + "%");
    IO.println("Checkout charges: quot; + checkout.total(50));
    IO.println("Same settings object? " + (settingsScreen.settings == checkout.settings ? "yes" : "no"));
}
Settings screen says: 10%
Checkout charges: $54
Same settings object? no
class Settings:
    def __init__(self):
        self.tax_percent = 8


class SettingsScreen:
    def __init__(self):
        self.settings = Settings()

    def set_tax(self, percent):
        self.settings.tax_percent = percent


class Checkout:
    def __init__(self):
        self.settings = Settings()

    def total(self, subtotal):
        return subtotal + subtotal * self.settings.tax_percent // 100


settings_screen = SettingsScreen()
checkout = Checkout()
settings_screen.set_tax(10)
print(f"Settings screen says: {settings_screen.settings.tax_percent}%")
print(f"Checkout charges: ${checkout.total(50)}")
print("Same settings object? " + ("yes" if settings_screen.settings is checkout.settings else "no"))
Settings screen says: 10%
Checkout charges: $54
Same settings object? no
class Settings {
  taxPercent = 8;
}

class SettingsScreen {
  settings = new Settings();
  setTax(percent) { this.settings.taxPercent = percent; }
}

class Checkout {
  settings = new Settings();
  total(subtotal) { return subtotal + Math.floor(subtotal * this.settings.taxPercent / 100); }
}

const settingsScreen = new SettingsScreen();
const checkout = new Checkout();
settingsScreen.setTax(10);
console.log(`Settings screen says: ${settingsScreen.settings.taxPercent}%`);
console.log(`Checkout charges: ${checkout.total(50)}`);
console.log("Same settings object? " + (settingsScreen.settings === checkout.settings ? "yes" : "no"));
Settings screen says: 10%
Checkout charges: $54
Same settings object? no
class Settings {
  taxPercent = 8;
}

class SettingsScreen {
  settings = new Settings();
  setTax(percent: number): void { this.settings.taxPercent = percent; }
}

class Checkout {
  settings = new Settings();
  total(subtotal: number): number { return subtotal + Math.floor(subtotal * this.settings.taxPercent / 100); }
}

const settingsScreen = new SettingsScreen();
const checkout = new Checkout();
settingsScreen.setTax(10);
console.log(`Settings screen says: ${settingsScreen.settings.taxPercent}%`);
console.log(`Checkout charges: ${checkout.total(50)}`);
console.log("Same settings object? " + (settingsScreen.settings === checkout.settings ? "yes" : "no"));
Settings screen says: 10%
Checkout charges: $54
Same settings object? no

The screen changed its settings object. Checkout made its own, which still says 8%. A $50 order should cost $55 at 10%; checkout charged $54.

  • The symptom: two copies of something the whole app should share, so a change made through one doesn't reach the other.
  • The cause: each part of the app says new Settings() for itself, so each one gets its own copy.

What would you try?

Tell everyone to use the screen's copy. Then checkout has to know about the settings screen to read a tax rate, and so does every other part that needs settings.

Make one settings object in a global variable everyone reads. It works, until someone writes settings = new Settings() somewhere and replaces it for everyone, or makes a second one anyway.

Make one at the start of the app and hand it to everyone who needs it. This one is better than it sounds, and it's the next lesson. First, the classic answer.

The classic fix: a class that allows only one

A house has one thermostat. However many rooms you walk through, turning it up turns up the one thermostat, and every room feels it.

A house drawn in cross-section with four rooms and a single thermostat on the hallway wall, set to 70, with lines running from it to a vent in every room

The Singleton pattern makes a class work like that thermostat. It does two things:

  1. It hides its constructor, so no other code can say new Settings().
  2. It hands out one shared object from one place, often a static Instance property or instance() method that makes the object the first time and gives back the same one every time after.

A role diagram: "the settings screen" and "checkout" each with an arrow labeled "asks for the settings" pointing to "the one way in" (Settings.instance), which points to a single box, "the only Settings object", inside a dashed fence labeled "only one, ever"

SettingsScreen settingsScreen = new SettingsScreen();
Checkout checkout = new Checkout();
settingsScreen.SetTax(10);
Console.WriteLine(quot;Settings screen says: {Settings.Instance.TaxPercent}%");
Console.WriteLine(quot;Checkout charges: ${checkout.Total(50)}");
Console.WriteLine("Same settings object? " + (ReferenceEquals(Settings.Instance, Settings.Instance) ? "yes" : "no"));

class Settings
{
    private static Settings? instance;

    private Settings() { }

    public static Settings Instance => instance ??= new Settings();

    public int TaxPercent { get; set; } = 8;
}

class SettingsScreen
{
    public void SetTax(int percent) => Settings.Instance.TaxPercent = percent;
}

class Checkout
{
    public int Total(int subtotal) => subtotal + subtotal * Settings.Instance.TaxPercent / 100;
}
Settings screen says: 10%
Checkout charges: $55
Same settings object? yes
static class Settings {
    private static Settings instance;
    int taxPercent = 8;

    private Settings() { }

    static Settings instance() {
        if (instance == null) {
            instance = new Settings();
        }
        return instance;
    }
}

class SettingsScreen {
    void setTax(int percent) { Settings.instance().taxPercent = percent; }
}

class Checkout {
    int total(int subtotal) { return subtotal + subtotal * Settings.instance().taxPercent / 100; }
}

void main() {
    SettingsScreen settingsScreen = new SettingsScreen();
    Checkout checkout = new Checkout();
    settingsScreen.setTax(10);
    IO.println("Settings screen says: " + Settings.instance().taxPercent + "%");
    IO.println("Checkout charges: quot; + checkout.total(50));
    IO.println("Same settings object? " + (Settings.instance() == Settings.instance() ? "yes" : "no"));
}
Settings screen says: 10%
Checkout charges: $55
Same settings object? yes
class Settings:
    _instance = None

    def __init__(self):
        self.tax_percent = 8

    @classmethod
    def instance(cls):
        if cls._instance is None:
            cls._instance = Settings()
        return cls._instance


class SettingsScreen:
    def set_tax(self, percent):
        Settings.instance().tax_percent = percent


class Checkout:
    def total(self, subtotal):
        return subtotal + subtotal * Settings.instance().tax_percent // 100


settings_screen = SettingsScreen()
checkout = Checkout()
settings_screen.set_tax(10)
print(f"Settings screen says: {Settings.instance().tax_percent}%")
print(f"Checkout charges: ${checkout.total(50)}")
print("Same settings object? " + ("yes" if Settings.instance() is Settings.instance() else "no"))
Settings screen says: 10%
Checkout charges: $55
Same settings object? yes
class Settings {
  static #instance = null;
  taxPercent = 8;

  static instance() {
    if (Settings.#instance === null) {
      Settings.#instance = new Settings();
    }
    return Settings.#instance;
  }
}

class SettingsScreen {
  setTax(percent) { Settings.instance().taxPercent = percent; }
}

class Checkout {
  total(subtotal) { return subtotal + Math.floor(subtotal * Settings.instance().taxPercent / 100); }
}

const settingsScreen = new SettingsScreen();
const checkout = new Checkout();
settingsScreen.setTax(10);
console.log(`Settings screen says: ${Settings.instance().taxPercent}%`);
console.log(`Checkout charges: ${checkout.total(50)}`);
console.log("Same settings object? " + (Settings.instance() === Settings.instance() ? "yes" : "no"));
Settings screen says: 10%
Checkout charges: $55
Same settings object? yes
class Settings {
  private static current: Settings | null = null;
  taxPercent = 8;

  private constructor() {}

  static instance(): Settings {
    if (Settings.current === null) {
      Settings.current = new Settings();
    }
    return Settings.current;
  }
}

class SettingsScreen {
  setTax(percent: number): void { Settings.instance().taxPercent = percent; }
}

class Checkout {
  total(subtotal: number): number { return subtotal + Math.floor(subtotal * Settings.instance().taxPercent / 100); }
}

const settingsScreen = new SettingsScreen();
const checkout = new Checkout();
settingsScreen.setTax(10);
console.log(`Settings screen says: ${Settings.instance().taxPercent}%`);
console.log(`Checkout charges: ${checkout.total(50)}`);
console.log("Same settings object? " + (Settings.instance() === Settings.instance() ? "yes" : "no"));
Settings screen says: 10%
Checkout charges: $55
Same settings object? yes

Now there's one settings object, and checkout charges the holiday rate.

Where the languages differ. C#, Java and TypeScript can make a constructor private, so new Settings() outside the class won't compile. Python and JavaScript can't; their version only asks politely, through instance(). But they rarely need the class at all: a module (a .py or .js file) runs once, however many files import it, so settings = Settings() in its own settings.py, or export const settings = new Settings() in settings.js, is already one shared object.

How it got its name

A singleton is a set with exactly one thing in it. The original 1994 book of patterns named the fix after that: a class with only one object, and one way in. Its other half, "reached from anywhere", is a kind of global state: data any part of the program can read and change. That's what made the fix work here, and it's also what the next lesson is about.

Where you've already used it

  • Java's Runtime.getRuntime() hands every caller the same object for the running program.
  • In a browser, window and document are one object each, shared by every script on the page.
  • Python's logging.getLogger("bakery") hands back the same logger every time you ask for that name.

When not to use it

The next lesson is all about this, because Singleton is the pattern teams regret most often. In short: a singleton is hidden (nothing in new Checkout() says it needs settings), and it's shared by everything, including tests that shouldn't share anything.

How often you'll meet it: now and then in app code, and often in older code (our estimate). You'll more often meet the safer version from the next lesson.

Check yourself

2 questions to try on the lesson page.

So what

When two parts of an app each make their own copy of something there should only be one of, you've found the smell Singleton answers. Knowing the classic fix matters, because you'll meet it in a lot of code; knowing why teams move away from it matters more.

Key terms

Cheat sheets