Design pattern: Singleton (TypeScript examples)
Tags: javascript, webdev, programming
Published: 2023-07-24 08:00:13

**Singleton is a creational design pattern that lets you ensure that a class has only one instance while providing a global access point to this instance.**

---

Here’s an example of implementing the Singleton pattern in TypeScript:

```typescript
class Singleton {
  private static instance: Singleton;

  private constructor() {
    // Private constructor to prevent direct instantiation
  }

  public static getInstance(): Singleton {
    if (!Singleton.instance) {
      Singleton.instance = new Singleton();
    }
    return Singleton.instance;
  }

  public someMethod(): void {
    console.log("Singleton method called");
  }
}

// Usage:
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();

console.log(instance1 === instance2); // Output: true

instance1.someMethod(); // Output: "Singleton method called"
```

In this example, the Singleton class has a private constructor to prevent direct instantiation. The getInstance method provides a way to access the singleton instance. When called for the first time, it creates a new instance of Singleton. On subsequent calls, it returns the existing instance.

When you run the code, you’ll see that instance1 and instance2 refer to the same object, indicating that only one instance of the Singleton class exists.

---
## When to use Singleton Design Pattern?

The Singleton design pattern is typically used in situations where you need to ensure that there is only one instance of a class and provide a global point of access to that instance. Here are some scenarios where the Singleton pattern can be useful:

- **Resource Sharing** : If you have a limited resource that needs to be shared among multiple parts of your application, such as a database connection, file system access, or a shared configuration, you can use a Singleton to manage that resource.

- **Global State**: In some cases, you may have a need for a global state that needs to be accessed and modified from different parts of your application. The Singleton pattern can be used to maintain and control that global state.

- **Logging and Error Handling**: Singletons can be helpful in managing logging or error handling systems. By using a Singleton, you can have a centralized point for logging and error reporting throughout your application.

- **Caching**: When you need to cache certain data to improve performance, a Singleton can be used to provide a single access point for retrieving and updating the cached data.
Database Operations: Singletons can be useful when dealing with database operations, such as connection pooling or managing a single connection to the database.

---

## Real-World Analogy

Imagine a government registry that stores information about citizens, such as their identification numbers, addresses, and other personal details. The government registry can be seen as a Singleton instance in this scenario.

Here’s how the analogy aligns with the Singleton pattern:

- **Single instance**: In a country, there is typically one central government registry that stores citizen information. Similarly, the Singleton pattern ensures that there is only one instance of the registry class throughout the application.

- **Global access**: The government registry serves as a central point for accessing and managing citizen information. Similarly, the Singleton instance provides global access to its methods and properties, allowing different parts of the application to access and update citizen data.

- **Controlled instantiation**: The government registry is established by the government itself and set up once. Similarly, the Singleton instance is created within the class itself, ensuring controlled and centralized instantiation.

- **Shared resource**: The government registry is a shared resource used by various government departments to retrieve and update citizen information. Similarly, the Singleton pattern can be used to manage and share resources like database connections, file access, or network connections that need to be accessed globally by different parts of the application.

In this example, the Singleton pattern ensures that all government departments interact with the same registry, avoiding the need for multiple instances and providing a centralized source of citizen information.

---

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c2zcidciydse9dofz4fs.png)


[![linkedin](https://img.shields.io/badge/linkedin-0A66C2?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/kristiyan-velkov-763130b3/)

<a href="https://revolut.me/kristiyanvelkov" target="_blank">
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rxmsw2d2ooukhdg8x5ar.png)
</a>

If you like my work and want to support me to work hard, please donate via:

<a href="https://revolut.me/kristiyanvelkov" title="Link to Revolut">Revolut website payment</a> or use the QR code above.                                                                                                                           


**Thanks a bunch for supporting me! It means a LOT 😍**