Singleton Pattern — Guarantee exactly one instance
One instance — watch global state and testability. · Often DI + single registration is cleaner than getInstance().
Watch
Watch, then scroll down for code and practice.
In code
class Config {
private static inst: Config | null = null;
private constructor() {}
static get instance() {
if (!this.inst) this.inst = new Config();
return this.inst;
}
}📘 Key ideas
The pattern
A class that ensures only one instance is ever created, providing a global point of access to it.
Thread safety problem
Two threads both see instance == null and both call new AppConfig(). Now you have two instances. The naive singleton is broken.
Fix: double-checked locking
Check null outside the lock (fast path), then check again inside (correctness). Or use a static inner class — Java classloader guarantees thread safety.
When to avoid it
Singletons make testing hard (global state). Consider dependency injection instead — inject one instance as a singleton without the class enforcing it.
🧠 Practice — Apply What You Learned
Factory Pattern: Notification Creator
A NotificationService creates different notification objects based on type: EMAIL, SMS, PU…
Builder Pattern: SQL Query Builder
Building a SQL query string by concatenating strings leads to bugs and unreadable code. De…
Singleton Pattern: Thread-Safe Config Manager
Design an AppConfig singleton that loads configuration from environment/file once and prov…
Observer Pattern: Stock Price Alerts
Design a StockMarket system where multiple observers (mobile app, email alert, dashboard w…
Decorator Pattern: Coffee Customisation
Design a coffee ordering system where a base Coffee can be decorated with add-ons (Milk, S…
Logger / Logging Framework
Design a flexible logging framework that supports multiple log levels, formatters, and out…
Food Delivery System (Swiggy/Zomato)
Design a food delivery platform where customers can browse restaurants, place orders, and …
Chat Application (WhatsApp-like)
Design a messaging system supporting 1-on-1 chats, group chats, message status, and media …
Notification System
Design a notification service that can send alerts via multiple channels based on user pre…
LRU Cache System
Design an in-memory cache system with LRU eviction policy, TTL support, and thread safety.…
Distributed Job Scheduler
Design a job scheduling system that can queue, execute, and monitor background jobs with r…
Social Media Feed (Twitter/Instagram)
Design a social media platform with posts, follows, and a personalized news feed.…
Rate Limiter
Design a rate limiting service that restricts request rates per user/IP using multiple alg…
🚀 Now apply what you learned
Pick a problem above, write your solution, and get AI feedback on your design.
Start Practice →