# Singleton

* 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));  
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://javascript-1.gitbook.io/design-pattern/creational-design-patterns/singleton.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
