Skip to the content

Lesson 270 of 296

Design patterns: adapter, decorator, repository, dependency injection and singleton

What you will learn

  • The adapter pattern
  • The decorator pattern (and how it differs from TypeScript decorators)
  • The repository pattern
  • Dependency injection as a pattern
  • The singleton pattern and its problems
On this page

Adapter

Problem: you want to use a class or library whose interface does not match what your code expects (a third-party SDK, a legacy API).
Solution: an adapter wraps it and exposes the interface your code wants.

TypeScript
export interface PaymentGateway {
  charge(customerId: string, amountPence: number): Promise<{ ok: boolean; reference: string }>;
}

type LegacyResult = { status: "SUCCESS" | "FAILED"; txn_ref: string };

export class LegacyPayClient {
  async makePayment(input: { cust: string; amountPounds: string }): Promise<LegacyResult> {
    return { status: Number(input.amountPounds) > 0 ? "SUCCESS" : "FAILED", txn_ref: `LP-${input.cust}` };
  }
}

export class LegacyPayAdapter implements PaymentGateway {
  constructor(private readonly client: LegacyPayClient) {}

  async charge(customerId: string, amountPence: number) {
    const result = await this.client.makePayment({ cust: customerId, amountPounds: (amountPence / 100).toFixed(2) });
    return { ok: result.status === "SUCCESS", reference: result.txn_ref };
  }
}

The rest of the app keeps using PaymentGateway (Lesson 267). The adapter translates names, units (pence to a pounds string) and result shapes. Adapters are how "ports and adapters" architecture plugs external systems in, and they keep vendor details in one file.

Decorator

Problem: add behaviour (logging, caching, retries, timing) to an object or function without changing it and without subclassing.
Solution: a decorator wraps the original with the same interface and adds behaviour before or after delegating.

TypeScript
export function withRetry(gateway: PaymentGateway, attempts = 3): PaymentGateway {
  return {
    async charge(customerId, amountPence) {
      let lastError: unknown;
      for (let i = 0; i < attempts; i++) {
        try {
          return await gateway.charge(customerId, amountPence);
        } catch (err) {
          lastError = err;
        }
      }
      throw lastError;
    }
  };
}

export function withLogging(gateway: PaymentGateway, log: (line: string) => void): PaymentGateway {
  return {
    async charge(customerId, amountPence) {
      log(`charging ${customerId} ${amountPence}p`);
      const result = await gateway.charge(customerId, amountPence);
      log(`charge ${result.ok ? "succeeded" : "failed"}: ${result.reference}`);
      return result;
    }
  };
}

Decorators stack: withLogging(withRetry(new LegacyPayAdapter(client)), console.log). The caller still sees a PaymentGateway. (Retries on payments must use idempotency keys, Lesson 195.) Express middleware and Nest interceptors (Lesson 209) are decorator-style.

Not the same thing: TypeScript's @Decorator syntax (used by NestJS, Lesson 207) attaches metadata or wraps class members at definition time. It is related in spirit but is a language feature, not the design pattern itself.

Repository

Problem: business logic mixed with SQL or ORM calls is hard to test and ties the domain to the database.
Solution: a repository looks like an in-memory collection of domain objects (findById, save, findByCustomer) and hides how they are stored.

TypeScript
export type Customer = { id: string; email: string; tenantId: string };

export interface CustomerRepository {
  findById(tenantId: string, id: string): Promise<Customer | null>;
  findByEmail(tenantId: string, email: string): Promise<Customer | null>;
  save(customer: Customer): Promise<void>;
}

export class InMemoryCustomerRepository implements CustomerRepository {
  private readonly rows = new Map<string, Customer>();

  async findById(tenantId: string, id: string) {
    const c = this.rows.get(id);
    return c && c.tenantId === tenantId ? c : null;
  }

  async findByEmail(tenantId: string, email: string) {
    for (const c of this.rows.values()) if (c.tenantId === tenantId && c.email === email) return c;
    return null;
  }

  async save(customer: Customer) {
    this.rows.set(customer.id, { ...customer });
  }
}

Production uses a PrismaCustomerRepository with the same interface; tests use the in-memory one (Lesson 206). Notice the tenant is required in every method, so tenant isolation (Lesson 203) is enforced by the repository's design. Do not over-generalise repositories into a generic Repository<T> that exposes every ORM feature; they should reflect the domain's real needs.

Dependency injection

Covered in depth in Lesson 208: an object receives its dependencies instead of creating them. It is what makes the repository, adapter and decorator patterns practical: the composition root (Nest's container, or a simple main.ts) builds the real objects and wires them together, while tests wire fakes:

const gateway = withLogging(withRetry(new LegacyPayAdapter(new LegacyPayClient())), console.log);
const checkout = new CheckoutService(gateway);

Singleton

Intent: a class has exactly one instance, with global access.

In Node.js, a module is evaluated once and cached, so exporting an instance already gives one instance per process:

export const prisma = new PrismaClient({ adapter });     one connection pool for the whole app

Legitimate uses: one database client or pool, one logger, configuration loaded once.

Problems with classic singletons (a class with a private constructor and a static getInstance()):

  • Hidden global state: any code can reach it, so dependencies are invisible in function signatures.
  • Hard to test: tests share state and cannot easily swap a fake.
  • Shared mutable state between requests causes bugs (Lesson 208's warning about storing the current user on a singleton service).

Better: create the single instance in the composition root and inject it. Nest providers are singletons by default but injected, which gives one instance without the hidden coupling. Interviewers often ask "what is wrong with singletons?"; the answer is global state and testability, not the idea of having one instance.

How to say it in an interview

"An adapter wraps a third-party or legacy API to match the interface my code expects, keeping vendor details in one place. A decorator wraps an object with the same interface to add logging, retries or caching, and decorators stack; it differs from TypeScript's decorator syntax, which attaches metadata. A repository presents persistence as a domain collection with methods like findById and save, so services are testable with in-memory fakes, and it can enforce tenant scoping. Dependency injection wires real or fake implementations together at a composition root. A singleton guarantees one instance, which Node modules give naturally, but classic singletons create hidden global state and hurt testing, so I prefer one instance created at startup and injected."

Key words

WordMeaning
AdapterTranslates one interface into another
Decorator (pattern)Wraps an object to add behaviour, keeping its interface
RepositoryA collection-like interface hiding data storage
Composition rootThe place where the application's objects are created and wired
SingletonA class with exactly one instance
Global stateData any part of the program can access and change

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.