DEV Community

Cover image for Learn Design Patterns: Mastering the Singleton Design Pattern
Sami Maachi
Sami Maachi

Posted on

Learn Design Patterns: Mastering the Singleton Design Pattern

Learn Design Patterns: Mastering the Singleton Design Pattern

The Singleton Pattern is one of the simplest and most commonly used design patterns in software development. Despite its simplicity, the Singleton Pattern can be incredibly powerful when used appropriately.

In this article, we will explore the Singleton Pattern, understand the problems it solves, and examine its implementation using TypeScript.

Table of Contents

  1. Singleton Pattern Definition

  2. Scenario: Understanding the Problem

  3. Real-Life Projects That Use the Singleton Pattern

1. Singleton Pattern Definition

The Singleton Pattern ensures a class can only have one instance and provides a global entry point to that instance. By centralizing object creation, it helps manage shared resources effectively and enforces consistent behavior across the system.

Key Characteristics of the Singleton Pattern

  1. Single Instance: Ensures only one instance of the class is created.

  2. Global Access Point: Provides a unified way to access a single instance throughout the application.

  3. Lazy Initialization: The instance is created only when it’s needed, optimizing resource usage.

  4. Thread Safety (if applicable): In multithreaded environments, ensures that the singleton instance is safely shared across threads.

2. Scenario: Understanding the Problem

Imagine you’re building a logging system for a complex application. Logs need to be written to a file or console, and it’s crucial to ensure only one logger instance manages these logs to avoid conflicts or redundancy. Without a Singleton, multiple logger instances could lead to scattered logs, inconsistent behavior, and resource wastage.

By implementing the Singleton Pattern, you guarantee that all parts of your application share the same logger instance, ensuring consistency and centralized control.

Implementation in TypeScript

class Logger {
  private static instance: Logger;
  private logs: string[] = [];

  private constructor() {}

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

  public log(message: string): void {
    this.logs.push(message);
    console.log(`Logged: ${message}`);
  }

  public showLogs(): void {
    console.log(this.logs);
  }
}

// Client code
const logger1 = Logger.getInstance();
logger1.log("First log entry");
const logger2 = Logger.getInstance();
logger2.log("Second log entry");
console.log("Are both instances the same?", logger1 === logger2); // true
logger1.showLogs();
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Private Constructor: Prevents the direct creation of objects using the new keyword.

  • Static Instance: Stores the single instance of the class.

  • Lazy Initialization: The instance is created only when it getInstance is called for the first time.

3. Real-Life Projects That Use the Singleton Pattern

  1. Configuration Management: Applications often use a Singleton to manage global configuration settings.

  2. Logging Systems: Loggers are a classic use case for Singletons, providing a centralized mechanism for writing logs.

  3. Database Connections: Singletons manage database connections to avoid overhead from creating multiple connections.

  4. Cache Management: Caching systems use Singletons to ensure a single source of truth for frequently accessed data.

Conclusion

The Singleton Pattern is a simple yet powerful design pattern that provides a controlled way to manage shared resources and enforce consistent behavior. While it’s crucial to avoid overusing it inappropriately, the Singleton Pattern can be an invaluable tool when applied to scenarios like configuration management, logging, and caching.

In the next article of our Learn Design Patterns series, we’ll explore the Structural Design Patterns by stating with the Adapter Pattern Stay tuned!

Top comments (0)