Algo-Sim › Design Patterns

Singleton: one shared instance

Easy · Design Patterns · step through it in Java, Python and C++ on your own input

A private constructor plus a static getInstance that creates the object once, so every caller shares the same instance and its state.

Problem

Several clients share one counter. increment(c) adds one and returns the new count, and read(c) returns the count, whichever client c asks. The counter class must allow only one instance, created on first use.

Constraints

Edge cases to test

Follow-up questions

How do you make lazy creation thread-safe in Java?
The holder-class idiom or an enum singleton; double-checked locking needs a volatile field.
Why is a singleton often a smell?
It is global state: hard to test and hidden coupling. Dependency injection of one shared instance usually works better.

Solution

Java

class Counter {
    private static Counter instance;              // the only one, created on first use
    private int count = 0;

    // Private: nobody else can call new.
    private Counter() {}

    public static Counter getInstance() {
        if (instance == null)
            instance = new Counter();
        return instance;
    }

    public int increment() {
        return ++count;
    }

    public int read() {
        return count;
    }
}

Python

class Counter:
    # The only one, created on first use.
    _instance = None

    def __init__(self):
        self.count = 0

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

    def increment(self):
        self.count += 1
        return self.count

    def read(self):
        return self.count

C++

#include <bits/stdc++.h>
using namespace std;
class Counter {
    int count = 0;
    Counter() {}
  public:
    Counter(const Counter &) = delete;
    Counter &operator=(const Counter &) = delete;
    static Counter &getInstance() {
        static Counter instance;
        return instance;
    }
    int increment() {
        return ++count;
    }
    int read() {
        return count;
    }
};

More Design Patterns problems