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
- A private constructor and a static accessor
- Every client gets the same instance and sees the same state
- In multi-threaded code, creation must be thread-safe
Edge cases to test
- Two threads calling
getInstanceat once - Tests that need a fresh instance
- Serialisation or reflection creating a second copy (Java)
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
volatilefield. - 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.countC++
#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
- Strategy: swappable discounts (Easy)
- Observer: publish and subscribe (Easy)
- State: a document workflow (Easy)
- Command: undo and redo (Medium)
- Chain of Responsibility: an ATM (Easy)
- Factory: create without naming classes (Easy)
- Builder: a pizza step by step (Easy)
- Decorator: stack toppings at runtime (Easy)
- Adapter: two legacy sensors, one interface (Easy)
- Proxy: a caching, lazy price service (Easy)
- Composite: folder sizes (Easy)