# Singleton

> Ensure a class has exactly one instance and provide a global access point to it — useful for shared resources like config, logging, or DB connections.

- **Category**: Software Design
- **Subcategory**: creational
- **Canonical URL**: https://designpattern.fyi/patterns/singleton/

---

## Description
**Intent**: Guarantee that only one instance of a class ever exists and provide a single, well-known access point to it.

**Context**: You have a database connection pool, configuration manager, or logger that should be initialized once and reused everywhere. Multiple instantiations would cause connection leaks, config conflicts, or duplicate log entries.

**Solution**: The class checks at construction time whether an instance already exists. If it does, return it; if not, create and store it. The constructor is effectively bypassed after the first call. The single instance is accessible globally through the class itself.


## Use Cases
Use for shared resources that must be initialized exactly once — DB connection pools, config managers, loggers, caches, or thread pools.



## Implementation Example

```javascript
class DatabaseConnection {
  constructor() {
    if (DatabaseConnection.instance) {
      return DatabaseConnection.instance;
    }
    this.connectionString = "mongodb://localhost:27017/db";
    DatabaseConnection.instance = this;
  }

  query(sql) {
    console.log(`Executing: ${sql}`);
  }
}

const instance1 = new DatabaseConnection();
const instance2 = new DatabaseConnection();
console.log(instance1 === instance2); // true

```



## Trade-offs


### Advantages

- Controlled access — one instance, one place to manage it.

- Lazy initialization — created only on first use, not at startup.




### Considerations & Drawbacks

- Global state in disguise — makes unit testing hard because state bleeds between tests.

- Violates Single Responsibility Principle — the class manages its own instantiation on top of its actual job.

- Can mask bad design — classes that 'need' a singleton often just have too many responsibilities.







---
**Reference**: [Original Source](https://refactoring.guru/design-patterns/singleton)

