---
name: singleton
description: This skill should be used when the user asks about "singleton pattern", "when to use singleton", "implement singleton", "global state", "single instance", or mentions needing exactly one instance of a class.
version: 1.0.0
---

# Singleton Pattern

## What Is It
The Singleton pattern ensures a class has only one instance and provides a global point of access to it. It combines two responsibilities: instantiating a single instance and providing global access to that instance.

## When to Use
- **Configuration managers** - Application-wide settings that need consistent access
- **Logging services** - Centralized logging that writes to a single output stream
- **Database connections** - Connection pools that manage limited resources
- **Cache systems** - Shared cache across application components
- **File system managers** - Coordinated file access operations
- **Hardware interface access** - Single point of access to hardware resources

## When NOT to Use
- **Testing scenarios** - Singletons create hidden dependencies, making unit tests difficult
- **Multi-threaded applications** - Race conditions can create multiple instances
- **Microservices/Distributed systems** - "Global" state doesn't work across process boundaries
- **When dependency injection is available** - DI containers provide better alternatives
- **When you need multiple instances** - If requirements change, refactoring is difficult

## How to Implement

### Basic Implementation Steps
1. Make the constructor private to prevent external instantiation
2. Create a private static instance variable
3. Create a public static method that returns the instance
4. Lazy initialization: create instance only when first requested

### TypeScript Implementation

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

  private constructor() {
    // Private constructor prevents external instantiation
  }

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

  public someBusinessLogic(): void {
    // Your business logic here
  }
}

// Usage
const singleton = Singleton.getInstance();
```

### Thread-Safe Implementation (Modern JS/TS)

```typescript
class Singleton {
  private static instance: Singleton;
  private static lock = false;

  private constructor() {}

  public static async getInstance(): Promise<Singleton> {
    if (!Singleton.instance) {
      if (!Singleton.lock) {
        Singleton.lock = true;
        Singleton.instance = new Singleton();
        Singleton.lock = false;
      } else {
        // Wait for initialization to complete
        while (!Singleton.instance) {
          await new Promise(resolve => setTimeout(resolve, 1));
        }
      }
    }
    return Singleton.instance;
  }
}
```

## Code Examples
See `examples/` directory for runnable TypeScript implementations:
- `examples/singleton.ts` - Basic implementation with lazy initialization
- `examples/singleton-advanced.ts` - Thread-safe and modern module-based approaches

## Related Patterns
- **Factory Method** - Can use Singleton to create concrete factory instances
- **Abstract Factory** - Often implemented as Singleton
- **Builder** - Can be implemented as Singleton for complex object construction
- **Facade** - Often implemented as Singleton since only one facade object is needed
- **State** - Often implemented as Singleton when state has no instance-specific data
