Design Patterns
Singleton, Factory, Strategy, Repository, Decorator, and more in NestJS.
26 minLevel 18 of 20
Patterns Nest uses daily
Nest is a pattern festival:
- Singleton — default provider scope
- Repository — data access abstraction
- Factory — custom providers (
useFactory) - Strategy — swappable algorithms via DI
- Decorator — TypeScript decorators + Nest middleware-style layers
- Adapter — wrap external SDKs behind ports
- Facade — modules exporting a clean API
- Command — CQRS commands/handlers (optional package)
Strategy
interface Pay { charge(n: number): string; }
class Card implements Pay { charge(n: number) { return "card:" + n; } }
class Cash implements Pay { charge(n: number) { return "cash:" + n; } }
class Checkout {
constructor(private pay: Pay) {}
run(n: number) { return this.pay.charge(n); }
}
console.log(new Checkout(new Card()).run(10));
console.log(new Checkout(new Cash()).run(10));Repository + Facade
Repositories isolate persistence. A module facade exports only the application service.
Repository
class UserRepo {
private data = new Map<string, string>();
save(id: string, name: string) { this.data.set(id, name); }
get(id: string) { return this.data.get(id); }
}
class UsersFacade {
constructor(private repo: UserRepo) {}
register(id: string, name: string) {
this.repo.save(id, name);
return this.repo.get(id);
}
}
console.log(new UsersFacade(new UserRepo()).register("1", "Ada"));Factory providers
When construction needs config or async init, Nest useFactory creates the instance — classic Factory pattern.
Factory fn
function createMailer(mode: string) {
return { send: (m: string) => console.log(mode, m) };
}
const mailer = createMailer("smtp");
mailer.send("hello");Check your understanding
5 questionsQuestion 1 of 5
Score: 0
Multiple choice