JavaScript
The Singleton pattern
Learn the Singleton pattern that ensures a single instance of a class.
The Singleton pattern
The Singleton pattern ensures that a class has only one instance. It is commonly used for configuration, caches or connections that must be shared.
In JavaScript we achieve this with a static instance property and a check inside the constructor. If the instance exists we return it; otherwise we create and store a new one.
This way the same configuration object is shared everywhere.
Singleton implementation
To implement a Singleton we start with static instance = null. The constructor returns AppConfig.instance if it is set; otherwise it assigns this to AppConfig.instance.
Often a static getInstance() method is added, so callers use it instead of new.
class AppConfig {
static instance = null;
constructor() {
if (AppConfig.instance) return AppConfig.instance;
AppConfig.instance = this;
}
}
Exercise AppConfig singleton
Declare a Singleton class named AppConfig. Start with static instance = null. The constructor should return AppConfig.instance if it is set; otherwise it assigns this to AppConfig.instance.
Show example solution
Start with class AppConfig, add static instance = null, in the constructor do if (AppConfig.instance) return AppConfig.instance;, then assign AppConfig.instance = this.
Example solution:
class AppConfig {
static instance = null;
constructor() {
if (AppConfig.instance) return AppConfig.instance;
AppConfig.instance = this;
}
}
Test yourself
-
What is the main goal of the Singleton pattern?
- Ensure only one instance of a class exists
- Sort objects
- Create many instances
- Hide the class
Show answer
Ensure only one instance of a class exists — Correct! Singleton guarantees a single instance.
-
Complete the Singleton assignment
class AppConfig {
static instance = null;
constructor() {
if (AppConfig.instance) return AppConfig.instance;
AppConfig.instance = ____;
}
}
Show answer
class AppConfig {
static instance = null;
constructor() {
if (AppConfig.instance) return AppConfig.instance;
AppConfig.instance = this;
}
}
-
Match the Singleton concepts
- Singleton
- Single instance guarantee
- static instance
- Class-level single instance
- getInstance()
- Instance access method
- Lazy init
- Create on first request
Next lesson: The Factory pattern