Skip to content

Creational Design Patterns in TypeScript: Singleton, Factory, Builder, Prototype

How Singleton, Factory, Builder, and Prototype patterns evolved in TypeScript: when ES modules replace singletons and when factory functions beat classes.

Ayhan Sipahi Ayhan Sipahi

Object instantiation in TypeScript rarely needs a Gang of Four pattern anymore. The default is the language feature: an ES module for a single shared instance, a factory function for conditional construction, object spread or structuredClone() for copies. Wrapping new in a class hierarchy that a module export already handles adds abstraction, harms testability, and obscures intent.

Singleton, Factory, Builder, and Prototype still earn their place, but the trigger is narrower than the textbooks suggest: shared configuration that many objects must apply consistently, or construction that has to be validated in steps.

Singleton Without the Class#

The Singleton pattern ensures a class has only one instance with global access. In 1994, this solved a genuine problem. In TypeScript it is usually an anti-pattern today, with a few narrow exceptions.

The Classic Problem#

Here’s the textbook singleton everyone learns:

class DatabaseConnection {
  private static instance: DatabaseConnection;
  private constructor() {
    // Private constructor prevents direct instantiation
  }

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

  query(sql: string): Promise<any> {
    // Database operations
  }
}

// Usage
const db = DatabaseConnection.getInstance();
await db.query('SELECT * FROM users');

This works, but it makes testing hard. You can’t easily mock the instance, can’t inject different configurations, and each test shares global state.

ES Modules as Natural Singletons#

ES modules are evaluated once and cached. Every file that imports the module gets the same exports, so a module-level variable holds one shared instance:

// db-connection.ts
class DatabaseConnection {
  constructor(private config: DatabaseConfig) {
    // Setup logic
  }

  async query(sql: string): Promise<unknown[]> {
    // Database operations
    return [];
  }
}

let instance: DatabaseConnection | undefined;

// Created on first call, not at import time
export function getDb(): DatabaseConnection {
  instance ??= new DatabaseConnection({
    host: process.env.DB_HOST ?? 'localhost',
    port: Number(process.env.DB_PORT ?? '5432'),
  });
  return instance;
}

// other-file.ts
import { getDb } from './db-connection';
await getDb().query('SELECT * FROM users');

// another-file.ts
import { getDb } from './db-connection'; // Same instance

The module system provides singleton behavior without the pattern’s complexity. The instance is created once, shared across imports, and testable through module mocking. The lazy getDb() matters: export const db = new DatabaseConnection(...) would read environment variables and open the connection the moment any file imports the module, including a test that only needs a helper or constant from it.

Where Module Singletons Break Down#

Module-level singletons assume one long-lived instance per process. That assumption breaks in four places:

  • Hot module replacement in development reloads the module and creates a new instance.
  • Server-side rendering needs an isolated instance per request.
  • Tests leak state through the shared instance from one run to the next.
  • Duplicate module copies. Node caches a module by where it resolves (ES modules by URL), so the same code loaded from two paths is two modules with two instances. This happens when a package is installed twice in node_modules at different versions, or when a package ships both CommonJS and ES module builds and both get loaded in one process (the dual package hazard). When a singleton shows up twice, run npm ls <package> to see every installed copy before debugging the class itself.

For the first three, tie each instance to its scope (a request, a test run): a factory function or a DI container that returns a fresh instance per call. For request scope in Node, AsyncLocalStorage carries one context through every callback and await of a request without passing it as a parameter:

import { AsyncLocalStorage } from 'node:async_hooks';
import { randomUUID } from 'node:crypto';
import express from 'express';

interface RequestContext {
  requestId: string;
}

const requestContext = new AsyncLocalStorage<RequestContext>();

const app = express();

// One fresh context per request; everything awaited inside next() sees it
app.use((req, res, next) => {
  requestContext.run({ requestId: randomUUID() }, next);
});

// Any module can read the current request's context without a parameter
export function currentContext(): RequestContext {
  const ctx = requestContext.getStore();
  if (!ctx) {
    throw new Error('currentContext() called outside a request');
  }
  return ctx;
}

getStore() returns undefined outside a run() call, so the guard turns a missing context into an error at the call site.

Dependency Injection Containers#

For complex applications, dependency injection containers manage object lifecycles:

// tsconfig.json: "experimentalDecorators": true, "emitDecoratorMetadata": true
import 'reflect-metadata'; // once, before the container is used
import { container, inject, injectable } from 'tsyringe';

interface DatabaseConfig {
  host: string;
  port: number;
}

@injectable()
class DatabaseConnection {
  constructor(@inject('DatabaseConfig') private config: DatabaseConfig) {
    // Setup logic
  }
}

@injectable()
class UserRepository {
  // No token needed: the parameter type is a class, so its metadata is the token
  constructor(private db: DatabaseConnection) {}
}

// Composition root: register the string token's value, then the singleton
container.register<DatabaseConfig>('DatabaseConfig', {
  useValue: {
    host: process.env.DB_HOST ?? 'localhost',
    port: Number(process.env.DB_PORT ?? '5432'),
  },
});
container.registerSingleton(DatabaseConnection);

const users = container.resolve(UserRepository); // receives the shared connection

DI containers give you singleton semantics with dependency injection benefits. Testing becomes straightforward: you swap implementations in the container.

The setup is part of the cost. tsyringe needs a Reflect polyfill and two compiler flags that keep the project on TypeScript’s legacy decorator implementation. The standard decorators that TypeScript 5.0 ships do not allow decorating parameters and are not compatible with emitDecoratorMetadata, so @inject() only works with experimentalDecorators. String tokens are also invisible to the compiler: drop the register call and resolve() fails at runtime with “Attempted to resolve unregistered dependency token”.

Logger and Feature-Flag Configuration#

A logger and a feature-flag store are the usual examples offered for an explicit class singleton: configure once at startup, read everywhere. The getInstance() versions of both carry the problems the next section warns about. A feature-flag check that runs before initialize() finishes silently returns false. A failed HTTP response gets parsed as if it had succeeded. fetch('/api/feature-flags') throws in Node, because a relative URL has no base to resolve against. A logger’s transport list survives from one test to the next with no way to reset it.

A module that hands out one instance built by a factory keeps the single shared instance. It fixes the early flag read, the unchecked HTTP status and the relative URL, and a test can build its own logger or flag store instead of resetting a shared transport list:

Logger with configured transports:

// logger.ts
export function createTransportLogger(transports: readonly Transport[]) {
  return {
    log(level: LogLevel, message: string): void {
      for (const t of transports) t.write(level, message);
    },
  };
}

let instance: ReturnType<typeof createTransportLogger> | undefined;

// The app's single instance, created on first call, not at import time
export function getLogger() {
  instance ??= createTransportLogger([
    new ConsoleTransport(),
    new FileTransport('/var/log/app.log'),
  ]);
  return instance;
}

getLogger().log('info', 'Application started');

// In a test: a fresh logger with an in-memory transport, nothing to reset
const lines: string[] = [];
const testLogger = createTransportLogger([
  { write: (level, message) => lines.push(`${level} ${message}`) },
]);

Feature flags with an init promise:

// feature-flags.ts
interface FlagRecord {
  name: string;
  enabled: boolean;
}

export function createFeatureFlags(loadFlags: () => Promise<FlagRecord[]>) {
  let flags: Map<string, boolean> | undefined;
  let ready: Promise<void> | undefined;

  return {
    // Idempotent: every caller awaits the same load; a failed load can be retried
    init(): Promise<void> {
      ready ??= loadFlags().then(
        (records) => {
          flags = new Map(records.map((r) => [r.name, r.enabled]));
        },
        (error: unknown) => {
          ready = undefined;
          throw error;
        },
      );
      return ready;
    },

    isEnabled(name: string): boolean {
      if (!flags) {
        throw new Error(`Flag "${name}" read before init() resolved`);
      }
      return flags.get(name) ?? false;
    },
  };
}

// The app's single instance. Nothing runs at import time.
export const flags = createFeatureFlags(async () => {
  // Node's fetch needs an absolute URL
  const response = await fetch(new URL('/api/feature-flags', process.env.CONFIG_BASE_URL));
  if (!response.ok) {
    throw new Error(`Feature flag load failed: HTTP ${response.status}`);
  }
  return (await response.json()) as FlagRecord[];
});

// main.ts: await once at startup, before serving traffic
await flags.init();

if (flags.isEnabled('new-dashboard')) {
  // Show new dashboard
}

// flags.test.ts: a separate instance, no network, no shared state
const testFlags = createFeatureFlags(async () => [{ name: 'new-dashboard', enabled: true }]);
await testFlags.init();

Every caller of init() awaits the same promise. An early isEnabled() call fails loudly where the class version quietly returned false. A test builds its own instance from the factory. That instance only reaches code that takes the logger or flags as a parameter or constructor dependency, as ApiClient does in the next section. A module that imports getLogger or flags directly still reads the app’s instance, so testing it needs module mocking.

Singleton for Injectable Dependencies#

Don’t use singleton for dependencies that should be injected:

// DON'T: Hard to test, can't swap implementations
class ApiClient {
  private static instance: ApiClient;
  private baseUrl = 'https://api.prod.com';

  private constructor() {}

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

// DO: Accept dependencies as constructor parameters
class ApiClient {
  constructor(
    private config: ApiConfig,
    private httpClient: HttpClient
  ) {}

  async get(endpoint: string): Promise<any> {
    return this.httpClient.get(`${this.config.baseUrl}${endpoint}`);
  }
}

// Production
const apiClient = new ApiClient(
  { baseUrl: 'https://api.prod.com' },
  new HttpClient()
);

// Testing
const apiClient = new ApiClient(
  { baseUrl: 'http://localhost:3000' },
  new MockHttpClient()
);

Factory Functions vs Factory Classes#

The Factory pattern encapsulates object creation logic. In TypeScript, you have choices: factory functions, factory classes, or discriminated unions with functions.

When Factory Functions Suffice#

Simple creation logic doesn’t need classes:

type LogLevel = 'debug' | 'info' | 'warn' | 'error';

function createLogger(level: LogLevel): Logger {
  switch (level) {
    case 'debug':
      return new DebugLogger();
    case 'info':
      return new InfoLogger();
    case 'warn':
      return new WarnLogger();
    case 'error':
      return new ErrorLogger();
  }
}

// Type-safe with exhaustive checking
const logger = createLogger('debug');

TypeScript’s exhaustive checking ensures you handle all cases. If you add a log level, the compiler catches missing implementations.

Shared Configuration Across Lambda Handlers#

Factory classes make sense when creation logic requires shared configuration:

import { Function, Runtime, Duration, ILayerVersion } from 'aws-cdk-lib/aws-lambda';
import { IVpc, ISecurityGroup, SubnetType } from 'aws-cdk-lib/aws-ec2';
import { Construct } from 'constructs';

class LambdaFunctionFactory {
  constructor(
    private vpc: IVpc,
    private layers: ILayerVersion[],
    private securityGroup: ISecurityGroup,
    private scope: Construct
  ) {}

  createApiHandler(config: ApiHandlerConfig): Function {
    return new Function(this.scope, config.id, {
      vpc: this.vpc,
      vpcSubnets: { subnetType: SubnetType.PRIVATE_WITH_EGRESS },
      securityGroups: [this.securityGroup],
      layers: this.layers,
      runtime: Runtime.NODEJS_24_X,
      timeout: Duration.seconds(30),
      memorySize: 1024,
      ...config,
    });
  }

  createWorkerHandler(config: WorkerConfig): Function {
    return new Function(this.scope, config.id, {
      vpc: this.vpc,
      vpcSubnets: { subnetType: SubnetType.PRIVATE_WITH_EGRESS },
      securityGroups: [this.securityGroup],
      layers: this.layers,
      runtime: Runtime.NODEJS_24_X,
      timeout: Duration.minutes(15),
      memorySize: 2048, // Workers need more memory
      ...config,
    });
  }

  createScheduledHandler(config: ScheduledConfig): Function {
    return new Function(this.scope, config.id, {
      vpc: this.vpc,
      vpcSubnets: { subnetType: SubnetType.PRIVATE_WITH_EGRESS },
      securityGroups: [this.securityGroup],
      layers: this.layers,
      runtime: Runtime.NODEJS_24_X,
      timeout: Duration.minutes(5),
      memorySize: 512, // Scheduled tasks typically lighter
      ...config,
    });
  }
}

// Usage in CDK stack
const factory = new LambdaFunctionFactory(
  vpc,
  [commonLayer, vendorLayer],
  lambdaSecurityGroup,
  this
);

const getUserHandler = factory.createApiHandler({
  id: 'GetUserHandler',
  handler: 'dist/handlers/get-user.handler',
  environment: { TABLE_NAME: usersTable.tableName },
});

const processJobWorker = factory.createWorkerHandler({
  id: 'ProcessJobWorker',
  handler: 'dist/workers/process-job.handler',
  environment: { QUEUE_URL: jobQueue.queueUrl },
});

This factory centralizes common Lambda configuration (VPC, layers, security groups) while allowing customization per function type. Without the factory, every Lambda definition would repeat the same 10-15 lines.

Discriminated Union Factories#

TypeScript’s discriminated unions enable type-safe factories:

type LoggerConfig =
  | { type: 'console'; colorize: boolean }
  | { type: 'file'; path: string; maxSize: number }
  | { type: 'cloudwatch'; logGroup: string; region: string };

function createLogger(config: LoggerConfig): Logger {
  switch (config.type) {
    case 'console':
      return new ConsoleLogger(config.colorize);
    case 'file':
      return new FileLogger(config.path, config.maxSize);
    case 'cloudwatch':
      return new CloudWatchLogger(config.logGroup, config.region);
  }
}

// TypeScript ensures correct properties for each type
const logger = createLogger({
  type: 'file',
  path: '/var/log/app.log',
  maxSize: 10485760, // 10MB
  // TypeScript error if we add 'colorize' here
});

The compiler verifies each configuration branch has exactly the right properties, catching missing or incorrect options before they become runtime errors.

Factory Functions with Type Guards#

Combine factories with type guards for runtime type checking:

type DatabaseConfig = PostgresConfig | MySQLConfig | SQLiteConfig;

interface PostgresConfig {
  type: 'postgres';
  socketPath: string;
  database: string;
}

interface MySQLConfig {
  type: 'mysql';
  host: string;
  port: number;
  connectionLimit: number;
}

interface SQLiteConfig {
  type: 'sqlite';
  filename: string;
}

function createDatabase(config: DatabaseConfig): Database {
  if (config.type === 'postgres') {
    return new PostgresDatabase(config.socketPath, config.database);
  }
  if (config.type === 'mysql') {
    return new MySQLDatabase(config.host, config.port, config.connectionLimit);
  }
  return new SQLiteDatabase(config.filename);
}

TypeScript narrows types in each branch, giving you autocomplete and type safety for branch-specific properties.

Progressive Construction with Builders#

The Builder pattern constructs complex objects step-by-step. In TypeScript, you must decide between a builder and an options object.

When Options Object Is Better#

For simple cases with few optional parameters, options objects are clearer:

interface LambdaOptions {
  handler: string;
  runtime?: Runtime;
  timeout?: number;
  memorySize?: number;
  environment?: Record<string, string>;
}

const fn = new Lambda({
  handler: 'index.handler',
  runtime: Runtime.NODEJS_24_X,
  timeout: 30,
  memorySize: 1024,
  environment: { TABLE_NAME: 'users' },
});

This is clean, type-safe, and self-documenting. No builder needed.

State-by-State Workflow Construction#

The Builder pattern earns its place on complex objects with dependencies and progressive configuration:

class StepFunctionsWorkflow {
  private states: State[] = [];
  private errorHandler?: ErrorHandler;

  addState(name: string, state: State): this {
    this.states.push({ name, ...state });
    return this;
  }

  addParallelStates(name: string, branches: State[][]): this {
    this.states.push({
      name,
      type: 'Parallel',
      branches,
    });
    return this;
  }

  onError(handler: (builder: ErrorPathBuilder) => ErrorPathBuilder): this {
    const errorPath = new ErrorPathBuilder();
    this.errorHandler = handler(errorPath).build();
    return this;
  }

  build(): StateMachine {
    if (this.states.length === 0) {
      throw new Error('Workflow must have at least one state');
    }

    return {
      states: this.states,
      errorHandler: this.errorHandler,
      startAt: this.states[0].name,
    };
  }
}

// Usage shows progressive disclosure
const workflow = new StepFunctionsWorkflow()
  .addState('ValidateInput', {
    type: 'Task',
    resource: validateLambda.functionArn,
  })
  .addParallelStates('ProcessData', [
    [
      {
        type: 'Task',
        resource: scanVirusLambda.functionArn,
        retry: [{ errorEquals: ['States.TaskFailed'], maxAttempts: 3 }],
      },
    ],
    [
      {
        type: 'Task',
        resource: extractMetadataLambda.functionArn,
        timeout: 60,
      },
    ],
    [
      {
        type: 'Task',
        resource: generateThumbnailLambda.functionArn,
        resultPath: '$.thumbnail',
      },
    ],
  ])
  .addState('StoreResults', {
    type: 'Task',
    resource: storeLambda.functionArn,
  })
  .onError((errorPath) =>
    errorPath
      .addState('LogError', {
        type: 'Task',
        resource: logErrorLambda.functionArn,
      })
      .addState('SendAlert', {
        type: 'Task',
        resource: alertLambda.functionArn,
      })
  )
  .build();

The builder provides:

  • Progressive disclosure: Error handling only available after adding states
  • Fluent API: Method chaining with autocomplete
  • Validation: build() validates complete configuration
  • Complex nesting: Parallel states and error handling compose cleanly

Type-Safe Builder with Generics#

Track required fields at compile time:

type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';

interface RequestConfig {
  url: string;
  method: HttpMethod;
  headers?: Record<string, string>;
  timeout?: number;
}

type RequiredFields = 'url' | 'method';

class RequestBuilder<TSet extends string = never> {
  // Type-only brand that ties TSet to the class shape.
  // `declare` emits no runtime field.
  declare private readonly __set: (fields: TSet) => void;

  private config: Partial<RequestConfig> = {};

  url(url: string): RequestBuilder<TSet | 'url'> {
    this.config.url = url;
    return this as RequestBuilder<TSet | 'url'>;
  }

  method(method: HttpMethod): RequestBuilder<TSet | 'method'> {
    this.config.method = method;
    return this as RequestBuilder<TSet | 'method'>;
  }

  headers(headers: Record<string, string>): this {
    this.config.headers = headers;
    return this;
  }

  timeout(ms: number): this {
    this.config.timeout = ms;
    return this;
  }

  // Callable only once both 'url' and 'method' are in TSet
  build(this: RequestBuilder<RequiredFields>): Request {
    const { url, method, headers, timeout } = this.config as RequestConfig;
    return new Request(url, {
      method,
      headers,
      signal: timeout ? AbortSignal.timeout(timeout) : undefined,
    });
  }
}

// @ts-expect-error: neither url nor method has been set
new RequestBuilder().build();

// @ts-expect-error: method is still missing
new RequestBuilder().url('https://api.example.com/users').build();

// OK: all required fields provided, in any order
const req = new RequestBuilder()
  .method('GET')
  .url('https://api.example.com/users')
  .headers({ Authorization: 'Bearer token' })
  .timeout(5000)
  .build();

The generic type parameter tracks which fields have been set, and build() is only callable when TSet includes all required fields. The __set brand is what makes that check real. TypeScript compares classes by structure, so without a member that uses TSet, RequestBuilder<never> and RequestBuilder<'url' | 'method'> have the same shape and every build() call compiles. Typing the brand as a function parameter makes the check run in the right direction: a builder that has set fewer fields cannot stand in for one that has set both.

The two @ts-expect-error lines turn the claim into a compile-time test. If someone removes the brand, tsc reports both directives as unused, and type-checking fails.

Builder with Factory Methods#

Combine patterns for common configurations:

class ApiClientBuilder {
  private config: Partial<ApiClientConfig> = {};

  // Factory methods for common configurations
  static forProduction(apiKey: string): ApiClientBuilder {
    return new ApiClientBuilder()
      .withApiKey(apiKey)
      .withTimeout(30000)
      .withRetries(3)
      .enableCaching()
      .withBaseUrl('https://api.prod.com');
  }

  static forDevelopment(apiKey: string): ApiClientBuilder {
    return new ApiClientBuilder()
      .withApiKey(apiKey)
      .withTimeout(60000)
      .disableCaching()
      .withVerboseLogging()
      .withBaseUrl('https://api.dev.com');
  }

  withApiKey(key: string): this {
    this.config.apiKey = key;
    return this;
  }

  withTimeout(ms: number): this {
    this.config.timeout = ms;
    return this;
  }

  withRetries(count: number): this {
    this.config.retries = count;
    return this;
  }

  enableCaching(): this {
    this.config.cacheEnabled = true;
    return this;
  }

  disableCaching(): this {
    this.config.cacheEnabled = false;
    return this;
  }

  withVerboseLogging(): this {
    this.config.logLevel = 'debug';
    return this;
  }

  withBaseUrl(url: string): this {
    this.config.baseUrl = url;
    return this;
  }

  build(): ApiClient {
    if (!this.config.apiKey) {
      throw new Error('API key is required');
    }
    if (!this.config.baseUrl) {
      throw new Error('Base URL is required');
    }
    return new ApiClient(this.config as ApiClientConfig);
  }
}

// Quick start with sensible defaults
const prodClient = ApiClientBuilder.forProduction(process.env.API_KEY);

// Or customize from scratch
const customClient = new ApiClientBuilder()
  .withApiKey(process.env.API_KEY)
  .withBaseUrl('https://api.custom.com')
  .withTimeout(45000)
  .withRetries(5)
  .build();

Reserve the builder for objects with 5+ optional parameters, complex validation dependencies, progressive configuration requirements, or a domain-specific language (DSL) that reads better as method chains than as a single object literal.

Replacing Prototype with Object Spread#

The Prototype pattern creates objects by cloning existing instances. JavaScript prototypes already share behavior between objects; copying the data is a separate job, and modern language features handle it.

Cloning via Object.create()#

The GoF Prototype asks an object for an independent copy of itself. Object.create(this) on its own does not produce one. It returns an empty object whose prototype is the original, so every read falls through to the original, and later changes to the original show up in the supposed clone. That is prototype delegation. A shallow copy keeps the prototype and copies the own fields:

class Prototype {
  // Shallow copy: same prototype (so methods and instanceof still work), own fields copied
  clone(): this {
    return Object.assign(Object.create(Object.getPrototypeOf(this)), this);
  }
}

class ConcretePrototype extends Prototype {
  constructor(public data: string, public tags: string[] = []) {
    super();
  }
}

const original = new ConcretePrototype('data', ['a']);
const clone = original.clone();

original.data = 'changed';
console.log(clone.data); // 'data': the clone has its own field
console.log(clone instanceof ConcretePrototype); // true

original.tags.push('b');
console.log(clone.tags); // ['a', 'b']: nested values are still shared

// Delegation for contrast: Object.create(original) has no own fields
const delegate = Object.create(original) as ConcretePrototype;
original.data = 'changed again';
console.log(delegate.data); // 'changed again': reads fall through to original

The copy is shallow, which is the same limit object spread has.

Object Spread for Shallow Clones#

Object spread handles shallow cloning cleanly:

const original = {
  name: 'John',
  age: 30,
  address: { city: 'NYC', zip: '10001' },
};

// Shallow clone
const clone = { ...original };

// Modify clone - doesn't affect original's primitive properties
clone.name = 'Jane';
console.log(original.name); // Still 'John'

// But nested objects are shared
clone.address.city = 'LA';
console.log(original.address.city); // Also 'LA'

For deep cloning, use structuredClone() (available in Node.js 17+ and widely available since Node 18 LTS, modern browsers):

const original = {
  name: 'John',
  age: 30,
  address: { city: 'NYC', zip: '10001' },
  metadata: {
    tags: ['developer', 'typescript'],
    preferences: { theme: 'dark' },
  },
};

// Deep clone
const deepClone = structuredClone(original);

// Modify nested properties - doesn't affect original
deepClone.address.city = 'LA';
deepClone.metadata.tags.push('react');
console.log(original.address.city); // Still 'NYC'
console.log(original.metadata.tags); // Still ['developer', 'typescript']

structuredClone() handles:

  • Nested objects and arrays
  • Dates, RegExp, Map, Set
  • Typed arrays
  • Cyclic references

It doesn’t handle:

  • Functions
  • DOM nodes
  • Symbols: symbol-keyed properties are skipped, and a symbol value throws DataCloneError
  • Prototypes (creates plain objects)

Immutable React State Updates#

React state updates demonstrate practical cloning:

const [state, setState] = useState({
  count: 0,
  items: ['apple', 'banana'],
  user: { name: 'John', role: 'admin' },
});

// Shallow clone with modification
setState(prev => ({ ...prev, count: prev.count + 1 }));

// Nested update: copy each changed path, share everything else
setState(prev => ({
  ...prev,
  items: [...prev.items, 'cherry'],
  user: { ...prev.user, role: 'user' },
}));

Test Fixtures with Shared Defaults#

A test data builder applies the Prototype idea to fixtures: a configured builder acts as the prototype, and each step returns a new builder that copies its template. The builder you call a method on never changes, so a shared admin template stays the same for every test that uses it:

const defaults: Omit<User, 'id' | 'email'> = {
  role: 'user',
  verified: false,
  permissions: [],
  createdAt: new Date('2025-01-01T00:00:00Z'),
  preferences: { theme: 'light', notifications: true },
};

class UserBuilder {
  private constructor(private readonly template: Partial<User>) {}

  static create(): UserBuilder {
    return new UserBuilder({});
  }

  // Every step returns a new builder; this one is never modified
  with(overrides: Partial<User>): UserBuilder {
    return new UserBuilder({ ...this.template, ...overrides });
  }

  asAdmin(): UserBuilder {
    return this.with({ role: 'admin', permissions: ['read', 'write', 'delete'] });
  }

  asVerified(): UserBuilder {
    return this.with({ verified: true });
  }

  withEmail(email: string): UserBuilder {
    return this.with({ email });
  }

  build(): User {
    const id = crypto.randomUUID();
    // structuredClone gives each user its own preferences, permissions and Date
    return structuredClone({
      id,
      email: `user-${id}@example.com`,
      ...defaults,
      ...this.template,
    });
  }
}

// Base admin template, reused across tests
const adminTemplate = UserBuilder.create().asAdmin().asVerified();

const admin1 = adminTemplate.withEmail('admin1@example.com').build();
const admin2 = adminTemplate.withEmail('admin2@example.com').build();

admin1.preferences.theme = 'dark';
console.log(admin2.preferences.theme); // 'light'
console.log(adminTemplate.build().email.startsWith('user-')); // true: no email leaked in

Spreading the template copies only its top level, so without structuredClone() in build() every user would share one preferences object and one Date. A test that changed preferences.theme would then change it for every other user built from the same defaults.

Trade-offs by Pattern#

PatternComplexityPerformanceTestingBundle size
SingletonES modules: zero boilerplate. DI containers: medium, needs framework knowledge and, for tsyringe, legacy decorator flags. Classic singleton: low, but carries testing overhead.Negligible; lazy initialization adds a small check on each access.Classic singleton shares state between tests. Module-based singletons mock through module mocks. DI containers make it straightforward.ES module approach is minimal. DI containers add real weight; check the container’s published bundle size before shipping it to a browser.
FactoryFunctions: low, straightforward. Classes: medium once configuration is shared. Discriminated unions: low complexity with strong type safety.Just a function call; no meaningful difference from direct instantiation.Pure functions or injectable dependencies test easily. Discriminated unions are testable branch by branch.Small: just functions or lightweight classes.
BuilderWorth the medium complexity past 5+ optional parameters. Type-safe generics push it to high complexity, justified for public library APIs. Immutable builders cost more memory but are safer under concurrency.Immutable builders create intermediate objects; mutable builders and plain method chaining add negligible overhead.Builders make excellent test fixtures; progressive configuration means testing each build step.Every builder method adds to the bundle. Immutable builders are larger than mutable ones. Type-safe builders compile away entirely (zero runtime cost).
PrototypeObject spread and structuredClone() are both very low complexity; custom cloning logic is needed only for special cases.Spread is fast for shallow clones; structuredClone() is slower but handles deep cloning correctly. Performance matters only for large objects or high-frequency cloning.Easy: pure data transformation, no side effects or hidden state.Negligible: built-in language features only.

The Default and Its Limits#

The default holds for most application code: export the instance from a module, write a factory function when construction branches, spread an object when you need a copy. TypeScript’s discriminated unions and generic constraints cover at compile time what the 1994 implementations had to enforce at runtime.

Override the default in three situations. Per-request isolation (SSR, request-scoped context) rules out module singletons, so create instances through a factory or a DI container and carry the request’s context in AsyncLocalStorage. Shared infrastructure configuration applied across many objects, such as the VPC, layers, and security groups on a set of Lambda functions, justifies a factory class. Construction that must be validated in steps, or that reads better as a small DSL, justifies a builder. Outside those three, the language feature does the same job with less code to maintain.

References#

Modern Perspective on Classic Design Patterns

Part 1 of 4

A comprehensive series examining how classic Gang of Four design patterns have evolved in modern TypeScript, React, and functional programming contexts. Learn when classic patterns still apply, when they've been superseded, and how to recognize underlying principles in modern codebases.

Related posts