# Singleton

## [About](https://refactoring.guru/design-patterns/singleton)

Used when you want to maintain **only one instance** of something in the application. *(Like DB instance, socket, etc)*

It does this by making the `constructor` private, so that only ONE static method *(like* `getInstance()`*)* from the class can call it, ONLY ONCE to instantiate it.

{% hint style="info" %}
This helps so that you do not need to pass these classes by parameters to dependency inject them.
{% endhint %}

{% hint style="danger" %}
**It can become an anti-pattern in data-shared environments with multi thread, since it won't be clear who should be mutating the state.**

*Ex.: It can lead to race conditions.*

To avoid multiple threads trying to create at the same time an instance, you must use a `lock` and recheck the `instance === null` inside the lock.
{% endhint %}

```typescript
class MyClass {
    private someProp: any;
    static instance: MyClass;
    
    private constructor (){}
    
    doSomething() {
        return this.someProp;
    }
    
    static getIntance() {
        if (!MyClass.intance) MyClass.instance = new MyClass();
        return MyClass.instance;
    }
}
```

On the outside you just call the `getInstance()` before using the Class.
