Design Patterns for Backend Code

Use classic Gang of Four and enterprise patterns to structure code, and recognize when they are overkill.

Intermediate · about 6 hours · difficulty 3/5

Learn first: Monoliths and Modular Monoliths

Design patterns are named, reusable solutions to recurring design problems. Knowing them gives you vocabulary ("wrap it in an adapter") and ready-made shapes, as long as you apply them to real problems rather than to show off.

Gang of Four patterns you will actually use

  • Strategy: swap algorithms behind an interface (different pricing or shipping calculators).
  • Adapter: wrap a third-party API (a payment provider) behind your own interface so it can be replaced and mocked.
  • Factory: centralize object creation when the concrete type depends on input or config.
  • Decorator: add behavior (caching, logging, retries) around an object without changing it; HTTP middleware is the same idea.
  • Observer: notify subscribers of events; the basis of in-process event emitters.
  • Singleton: one shared instance (a DB pool). Use sparingly; it becomes hidden global state that complicates tests.
  • Builder and Facade for complex construction and simplifying a messy subsystem.

Enterprise application patterns

  • Repository: a collection-like interface over data access, keeping SQL out of business logic.
  • Unit of Work: track changes and commit them in one transaction (what most ORMs do).
  • Dependency injection: pass collaborators in rather than creating them inside, which makes testing easy. Frameworks like NestJS, Spring and ASP.NET build on it.
  • Middleware / chain of responsibility for request pipelines.

Principles behind them

SOLID, composition over inheritance, and "program to an interface" explain why the patterns work.

Pitfalls

Pattern-itis: factories of factories and interfaces with one implementation that never changes. Start simple and refactor to a pattern when the pain appears.

You are ready to move on when you can spot three patterns in your framework of choice and refactor one piece of your code to use Adapter or Strategy with a test proving the swap works.

Key concepts

  • Strategy and Adapter
  • Factory and Builder
  • Decorator and middleware
  • Observer
  • Repository and Unit of Work
  • Dependency injection
  • SOLID principles
  • Singleton and its pitfalls

Mini project

Wrap two email providers behind one Adapter interface, select between them with a Strategy based on config, inject it into your service, and unit test the service with a fake.

Check yourself

How does HTTP middleware relate to the Decorator and Chain of Responsibility patterns?

Free resources