> For the complete documentation index, see [llms.txt](https://javascript-1.gitbook.io/design-pattern/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://javascript-1.gitbook.io/design-pattern/creational-design-patterns/singleton.md).

# Singleton

A class of which only a single instance can exist.

* A class has only one instance and provides a global point of access.
* It's usage is high in javascript libraries.
* It limits the number of instance of particular object to one, a single instance called as singleton.
* Reduces the need for global variables because it limits namespace collision and associated risk of name collision.
* Module pattern is manifestation(a symptom) of singleton pattern.
* Several other patterns, such as, Factory, Prototype, and Facade are frequently implemented as Singletons when only one instance is needed.

```javascript
EX:
var Singleton = (function () {
    var instance;
 
    function createInstance() {
        var object = new Object("I am the instance");
        return object;
    }
 
    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();
 
function run() {
 
    var instance1 = Singleton.getInstance();
    var instance2 = Singleton.getInstance();
 
    alert("Same instance? " + (instance1 === instance2));  
}
```
