This Is The Way: Singleton Pattern & Use Cases
Published: 2021-09-14 20:37:43

Okay folks, today I’ll be starting new episodes called “This Is The Way”. I know the name is somehow catchy already. But I can assure you that the content will be even more delightful to read.

Well, we’ll start with design patterns and their 'could be real' cases. First of all, design patterns are broken into three categories. We call it *Gang of Four (GoF) design patterns*.

> Actually 'four' in the name is not related to category count. It's related to the book called *Design Patterns: Elements of Reusable Object-Oriented Software* where there are four authors. You can check out more [here](https://springframework.guru/gang-of-four-design-patterns/).

Here is the list:

1. Creational -> for the creation of objects,
2. Structural -> to provide relationship between objects,
3. Behavioral -> to help define how objects interact.

&nbsp;
![Types of Design Patterns](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bohgtfokvfrh9mhzvhxw.png)

&nbsp;
There are definitely more patterns than the above list. But these are most used patterns across JavaScript projects. Probably you will only need these ones so we will go through each. Also we need to understand that every pattern is one proven solution for one common problem. Don’t forget to give attention what problem they’re trying to solve beforehand.

Our topic for today is **Singleton pattern**. Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code. The problem it’s trying to solve is:

You probably have utility classes for certain operations (it can be Log, Database, Audio or File I/O etc.) where only one instance must exist during application lifetime. Why you ever need one instance of a class? Your concerns could be:

* Memory management,
* Shared resource,
* Game modding (ex. You have only one instance of the mod for player’s lifetime),
* Literally don’t need more instances than one (ex. Pure utility class with only helper functions whatsoever)

&nbsp;
Actually, I had to use the Singleton pattern for one of the mods I developed regarding the Cyberpunk 2077 game very recently. First we can start with,

* Why do we need to use such a pattern in the first place?
* What are the use cases in the real world that we need to create such a pattern inside our softwares & projects? etc.

&nbsp;
It comes from a very basic need and at the same time very logical reason to use such a pattern. Main goal here is let's say you have one common utility class across your project and wanna use this class all over the place. But if you just try to initialize a new instance every time you need this class, it will probably be a disaster from a development perspective. Because that means you need to create an object which will take up some part of memory every time you use it. Let’s examine the examples below for better understanding:

```typescript
class MyUtilityClass {
  private _counter: number = 0

  public myUtilityMethod (): void {
    console.log(`Current value of counter is ${this._counter++}`)
  }
}

function someFunctionality (): void {
  const instance1: MyUtilityClass = new MyUtilityClass()
  const instance2: MyUtilityClass = new MyUtilityClass()

  console.log('')
  instance1.myUtilityMethod()
  instance2.myUtilityMethod()
  console.log('')

  console.log(`Singleton ${instance1 === instance2 ? 'works' : 'fails'}`)
}

someFunctionality()
```

> counter property only exists to demonstrate reinitializing of utility class every time. It's not part of a real life case.

&nbsp;
Output will be like,
```
PS [hidden-path]\singleton-pattern> yarn start
yarn run v1.22.11
$ ts-node ./index.ts

Current value of counter is 0
Current value of counter is 0

Singleton fails
```

&nbsp;
As you can see, it's not logical to initialize a new instance every time we need it for our common helper class. Instead we can make it a singleton to use across the whole project. Like this,

```typescript
class MyUtilityClass {
  /**
   * You should declare a field for storing singleton instance
   */
  private static _instance: MyUtilityClass

  /**
   * The constructor must be private for preventing initialization
   * of the class itself. Also you can try to throw an exception
   * in case of initialization of the class through plain JavaScript
   */
  private constructor () {}

  /**
   * The static getter for singleton instance. You may wanna use
   * static method instead for initializing the class with some params
   */
  public static get Instance (): MyUtilityClass {
    if (this._instance === undefined) {
      this._instance = new this()
    }

    return this._instance
  }

  /**
   * Lastly, you should define some helper functions
   */
  private _counter: number = 0

  public myUtilityMethod (): void {
    console.log(`Current value of counter is ${this._counter++}`)
  }
}

function someFunctionality (): void {
  const instance1: MyUtilityClass = MyUtilityClass.Instance
  const instance2: MyUtilityClass = MyUtilityClass.Instance

  console.log('')
  instance1.myUtilityMethod()
  instance2.myUtilityMethod()
  console.log('')

  console.log(`Singleton ${instance1 === instance2 ? 'works' : 'fails'}`)
}

someFunctionality()
```

&nbsp;
Output will be like,
```
PS [hidden-path]\singleton-pattern> yarn start
yarn run v1.22.11
$ ts-node ./index.ts

Current value of counter is 0
Current value of counter is 1

Singleton works
```

There are more ways to define a singleton class for TypeScript & JavaScript projects. Even there could be potentially unexpected results when you compile your TypeScript code into JavaScript. You can check out more via this [StackOverFlow question](https://stackoverflow.com/questions/30174078/how-to-define-singleton-in-typescript).

Also there could be bottlenecks of using singleton in the first place. Most of the time, it only applies to classic backend languages such as C#, Java etc. We both know that JavaScript is way more flexible than these ones. Furthermore, you can bypass most of the cases. But of course it's a good idea to check them anyway for expanding your understanding about singletons via this [StackOverFlow question](https://stackoverflow.com/questions/1392315/problems-with-singleton-pattern).

GitHub repo link for Singleton pattern we implemented: https://github.com/b8kkyn/typescript-singleton-pattern