AI solution for Interview Question on BFE.dev
116. What is Singleton Pattern?
Singleton Pattern is a design pattern that restricts the instantiation of a class to a single instance and ensures that the instance is globally accessible. It is a Creational Pattern that allows us to create only one instance of a class and provide a global point of access to it.
In JavaScript, we can implement Singleton Pattern using an object literal or an Immediately Invoked Function Expression (IIFE). The key idea is to create a single instance of an object and return that instance every time the Singleton is requested.
For example, here is a simple implementation of a Singleton using an object literal:
const mySingleton = {
prop1: 'value',
prop2: 'value',
method1: function() {
console.log('method 1');
}
};
// Access the Singleton instance
mySingleton.method1();
console.log(mySingleton.prop1);
This implementation creates a single object (mySingleton
) that contains some properties and methods. Whenever we want to access the Singleton instance, we simply refer to mySingleton
.
Overall, Singleton Pattern is useful when we want to ensure that only one instance of a class is created, such as when we are working with resource-intensive objects like databases or network connections.