# Singleton

## Intent

* Restrict the instantiation of a class to a singular instance.
* Provide easy access to that instance.

## Problems

* How to avoid global instances that pollute global namespace and permit lazy/eager instantiation.
* How to ensure only one instance of a class is ever created.
* How to provide universal and easy access to that single instance.

## Solution

* Make the default constructor private, to prevent other objects from using the new operator with the Singleton class.
* Create a static creation method that acts as a constructor. Under the hood, this method calls the private constructor to create an object and saves it in a static field. All following calls to this method return the cached object.

## Advantages

✅ You can be sure that a class has only a single instance.\
✅ You gain a global access point to that instance.\
✅ The singleton object is initialized only when it’s requested for the first time.<br>

## Disadvantages

❌ Some consider the singleton to be an anti-pattern that introduces global state into an application, often unnecessarily.\
❌ Increased coupling to a singleton instance can introduce difficulties with unit testing.\
❌ Singletons also violate the **single-responsibility principle** because they are responsible for enforcing their own uniqueness along with performing their normal functions.\
❌ The pattern requires special treatment in a multi-threaded environment so that multiple threads won’t create a singleton object several times.\
❌ It may be difficult to unit test the client code of the Singleton because many test frameworks rely on inheritance when producing mock objects. Since the constructor of the singleton class is private and overriding static methods is impossible in most languages, you will need to think of a creative way to mock the singleton. Or just don’t write the tests. Or don’t use the Singleton pattern.<br>

## Implementation

* Singleton can be implemented by,
  1. Eager Initialization
  2. Lazy Initialization *(thread safe)*
  3. Thread-safe implementation
     * Double check locking
     * Inner static class
  4. Enum based Singleton

***

#### Note

💡 Is Singleton pattern still part of GoF pattern, read what GoF authors have to say about it [here](https://www.informit.com/articles/article.aspx?p=1404056). 💡 How single is singleton in Java, read more about it [here](https://web.archive.org/web/20051117213814/http://weblogs.java.net:80/blog/kirillcool/archive/2005/08/how_single_is_y.html). 💡 Breaking singleton in Java, interesting read [here](https://stackoverflow.com/questions/20421920/what-are-the-different-ways-we-can-break-a-singleton-pattern-in-java)


---

# 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://anon-coders-notes.gitbook.io/techwriterdev/softwareengineering/designpatterns/notes/03_creational/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.
