The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. This is useful when exactly one object is needed to coordinate actions across the system.
class Singleton {
// Constructor function for the Singleton class
constructor() {
// Check if an instance already exists
if (!Singleton.instance) {
// If no instance exists, assign the current instance to Singleton.instance
Singleton.instance = this;
}
// Return the single instance
return Singleton.instance;
}
// Example method for the Singleton class
someMethod() {
console.log("Singleton method called");
}
}
Class Declaration: The Singleton
class is declared.
Constructor: The constructor checks if an instance of the class already exists.
if (!Singleton.instance)
: This condition checks ifSingleton.instance
isundefined
ornull
.Singleton.instance = this
: If no instance exists, the current instance (this
) is assigned toSingleton.instance
.return Singleton.instance
: The constructor returns the single instance of the class.
Method: The someMethod
is a simple method that logs a message to the console.
// Create the first instance of the Singleton class
const instance1 = new Singleton();
// Attempt to create a second instance of the Singleton class
const instance2 = new Singleton();
// Check if both instances are the same
console.log(instance1 === instance2); // true
// Call the method on the first instance
instance1.someMethod(); // Singleton method called
Instance Creation:
const instance1 = new Singleton()
: Creates the first instance of theSingleton
class.const instance2 = new Singleton()
: Attempts to create a second instance, but due to theSingleton
pattern, it returns the same instance asinstance1
.
Instance Comparison:
console.log(instance1 === instance2)
: This logs true because bothinstance1
andinstance2
refer to the same instance.
Method Call:
instance1.someMethod()
: Calls thesomeMethod
on the singleton instance, logging "Singleton method called" to the console.
The Singleton pattern is useful for ensuring that a class has only one instance and provides a global point of access to that instance. This is particularlly beneficial in scenarios where a single shared resource is needed througout an application. By controlling the instantiation process, the Singleton pattern helps manage resources efficiently and ensures consistent behavior across the application.