← Back to scenarios
ScenarioCatalog DB

Cache manager singleton

Maintain one shared in-memory cache so all application components reuse the same stored data.

Problem

An application must coordinate access to one shared in-memory cache without creating separate cache instances that duplicate data or produce inconsistent cached values.

Related patterns

Implementations

Singleton

TypeScriptApplication

Singleton in TypeScript

Provides one lazily initialized application configuration store with a controlled shared access point.

TypeScript
class ApplicationConfig {
  private static instance: ApplicationConfig | undefined;

  private readonly values = new Map<string, string>();

  private constructor() {
    this.values.set("region", "us-east-1");
  }

  static getInstance(): ApplicationConfig {
    if (!ApplicationConfig.instance) {
      ApplicationConfig.instance = new ApplicationConfig();
    }

    return ApplicationConfig.instance;
  }

  get(key: string): string | undefined {
    return this.values.get(key);
  }

  set(key: string, value: string) {
    this.values.set(key, value);
  }
}

const configA = ApplicationConfig.getInstance();
const configB = ApplicationConfig.getInstance();

configA.set("feature.checkoutV2", "enabled");

console.log(configA === configB); // true
console.log(configB.get("feature.checkoutV2")); // enabled

Associated technologies