Back to blog

cat blog/les-patterns-de-conception-que-jutilise-au-quotidien.md

·Patterns·10 min read

The design patterns I use every day

Solution Architect

The design patterns I use every dayThe design patterns I use every day
Contents
  1. The Gang of Four's three families
  2. Creational: controlling how objects are built
  3. Singleton
  4. Factory
  5. Builder
  6. Structural: assembling without coupling everything
  7. Adapter
  8. Decorator
  9. Facade
  10. Proxy
  11. Behavioral: distributing responsibilities
  12. Strategy
  13. Observer
  14. Command
  15. State
  16. The Repository: outside the GoF, but essential
  17. Summary: where I find them
  18. The trap: over-engineering
  19. Up next
  20. Sources

In the previous article, What code review taught me while leading a team, I described how the same comments kept coming back in review, until we put names on them. Those names are design patterns. This article opens the announced series.

A design pattern is a reusable solution to a problem that comes up often when designing software. It isn't code to copy, but a model you adapt to your project. Patterns were popularized in 1994 by the book Design Patterns: Elements of Reusable Object-Oriented Software, written by four authors nicknamed the Gang of Four (GoF).

I won't recite the catalog. I'll show where I run into these patterns every week in Laravel, NestJS and Flutter, often without having written them myself, because the frameworks already use them.

The Gang of Four's three families

The GoF classified its 23 patterns into three families, depending on the problem they solve: creating objects, assembling objects, or organizing how they collaborate.

Patterns GofPatterns Gof

I don't use all 23. Eleven keep coming back in my code, often because Laravel, NestJS or Flutter already apply them for me. Those are the ones I detail below.

Creational: controlling how objects are built

Creational patterns make object instantiation flexible and decoupled from the rest of the code.

Singleton

The problem: an SMS client or a connection recreated on every call, when a single instance is enough.

The classic Singleton, with a static getInstance() method, is now considered a trap: it's hidden global state, hard to replace in tests. I never write it by hand. I let the dependency injection container guarantee the single instance:

// Laravel — AppServiceProvider
$this->app->singleton(SmsClient::class, fn () => new SmsClient(
    apiKey: config('services.sms.key'),
));
// NestJS — providers are singletons by default
@Injectable()
export class SmsClient {
  constructor(private readonly config: ConfigService) {}
}
// Flutter — with get_it
final getIt = GetIt.instance;
getIt.registerLazySingleton<ApiClient>(() => ApiClient(baseUrl: env.apiUrl));

The instance is unique, but it stays injectable: in tests, I replace it with a fake in one line.

Factory

The problem: if statements and new calls scattered around to create the right object depending on context.

The Factory centralizes that decision. I use it when creation depends on data, for example the notification channel chosen by the user:

final class NotifierFactory
{
    public function __construct(private Container $container) {}

    public function make(Channel $channel): Notifier
    {
        return match ($channel) {
            Channel::Sms => $this->container->make(SmsNotifier::class),
            Channel::Email => $this->container->make(EmailNotifier::class),
            Channel::WhatsApp => $this->container->make(WhatsAppNotifier::class),
        };
    }
}

A small source of confusion: Laravel's model factories (User::factory()->create()) generate test data. They're inspired by the same principle, but serve a different need.

Builder

The problem: building a complex object step by step, without a twelve-parameter constructor.

I rarely write one, but I use them constantly: Eloquent's Query Builder and Laravel's HTTP client are perfect examples.

$response = Http::withToken($token)
    ->timeout(10)
    ->retry(3, 200)
    ->acceptJson()
    ->post($url, $payload);

Each method adds a step to building the request, and post() fires it. On the TypeScript side, TypeORM's QueryBuilder follows the same logic.

Structural: assembling without coupling everything

Structural patterns explain how to assemble classes into larger structures while keeping those structures flexible.

Adapter

The problem: every external provider (SMS, payment, storage) has its own API, and switching providers means rewriting business code.

This is probably the pattern that has saved me the most time. Business code only knows an interface of my own; one adapter per provider translates to the real API:

// The contract business code knows
export interface SmsSender {
  send(to: string, message: string): Promise<void>;
}

// One adapter per provider
@Injectable()
export class TwilioSmsAdapter implements SmsSender {
  constructor(private readonly twilio: Twilio) {}

  async send(to: string, message: string): Promise<void> {
    await this.twilio.messages.create({ to, from: process.env.SMS_FROM, body: message });
  }
}
// The module picks the adapter; the rest of the code never changes
{ provide: 'SmsSender', useClass: TwilioSmsAdapter }

The day you need to switch to a local carrier, you just write a new class and change one line of configuration.

Decorator

The problem: adding behavior (caching, logging, timing) without modifying the original class.

Example: a CachedProductRepository wraps the real repository, implements the same interface and only hits the database when the value isn't cached. Beware a common confusion: NestJS's TypeScript decorators (@Controller, @Injectable) are a language feature for adding metadata, not the GoF Decorator pattern.

Facade

The problem: a complex subsystem you want to expose behind a simple interface.

I write facades when one operation chains several services: a CheckoutService that calls stock, payment and invoicing behind a single checkout() method. Another classic confusion: Laravel's Facades (Cache::get(), Mail::to()) are, according to the documentation itself, "static proxies" to services in the container. The name is misleading.

Proxy

The problem: controlling access to an object, loading it later or caching its result.

Eloquent uses it for lazy loading relationships: $order->customer only fires the query on first access. It's handy… and it's exactly what causes the N+1 queries mentioned in the code review article.

Behavioral: distributing responsibilities

Behavioral patterns deal with communication between objects and how roles are distributed.

Strategy

The problem: a switch that grows with every new case. The classic: payment methods.

// Before: every new payment method modifies this method
public function pay(Order $order, string $method): PaymentResult
{
    switch ($method) {
        case 'tmoney': /* 30 lines */ break;
        case 'flooz':  /* 30 lines */ break;
        case 'card':   /* 30 lines */ break;
    }
}
// After: one interchangeable strategy per payment method
interface PaymentGateway
{
    public function charge(Order $order): PaymentResult;
}

final class TMoneyGateway implements PaymentGateway { /* ... */ }
final class FloozGateway implements PaymentGateway { /* ... */ }
final class CardGateway implements PaymentGateway { /* ... */ }

final class PaymentService
{
    /** @param array<string, PaymentGateway> $gateways */
    public function __construct(private array $gateways) {}

    public function pay(Order $order, string $method): PaymentResult
    {
        $gateway = $this->gateways[$method]
            ?? throw new UnsupportedPaymentMethod($method);

        return $gateway->charge($order);
    }
}

Adding a payment method means adding a class, without touching existing code. That's the open/closed principle we'll meet again in the SOLID article.

Observer

The problem: side effects (email, SMS, analytics) glued to business code, which grows with every new reaction.

The object that changes state publishes an event; those interested subscribe. All three frameworks build it in:

// Laravel: the action publishes, listeners react
OrderPlaced::dispatch($order);

final class SendOrderConfirmation
{
    public function handle(OrderPlaced $event): void
    {
        Mail::to($event->order->customer)->send(new OrderConfirmed($event->order));
    }
}
// NestJS, with @nestjs/event-emitter
@OnEvent('order.placed')
async onOrderPlaced(event: OrderPlacedEvent) {
  await this.mailer.sendConfirmation(event.orderId);
}

In Flutter, ChangeNotifier and Stream rest on the same principle: the widget subscribes and rebuilds when state changes. We'll come back to it in the state management article.

Command

The problem: turning an action into a standalone object you can queue, replay or undo.

Laravel jobs are its direct application: ProcessPayment::dispatch($order) creates an object holding everything it needs to run later, in another process. On the NestJS side, the @nestjs/cqrs module formalizes the pattern with its CommandBus and CommandHandler.

State

The problem: an object whose behavior depends on its state, and if ($order->status === ...) everywhere.

I often use a lightweight version with PHP enums, which centralize the allowed transitions:

enum OrderStatus: string
{
    case Pending = 'pending';
    case Paid = 'paid';
    case Shipped = 'shipped';
    case Cancelled = 'cancelled';

    public function canTransitionTo(self $next): bool
    {
        return in_array($next, match ($this) {
            self::Pending => [self::Paid, self::Cancelled],
            self::Paid => [self::Shipped, self::Cancelled],
            self::Shipped, self::Cancelled => [],
        }, true);
    }
}

The full State pattern, with one class per state, is justified when each state has many behaviors of its own. In Flutter, Bloc comes close: each screen state (loading, success, error) is a distinct object.

The Repository: outside the GoF, but essential

The Repository isn't one of the Gang of Four's 23 patterns. It comes from enterprise architecture literature, notably Martin Fowler's Patterns of Enterprise Application Architecture and Eric Evans's Domain-Driven Design. But it's one of the most debated in review, so it deserves its place here.

Its role: isolate data access behind an interface, as if objects lived in an in-memory collection. Business code asks for "this customer's pending orders" without knowing whether they come from MySQL, an API or a cache.

My use depends heavily on the technology:

  • In Laravel, I mostly avoid it. Eloquent follows the Active Record pattern: the model is already data access. Adding an OrderRepository that just calls Order::where(...) doubles the code for nothing. I prefer query scopes and actions.

  • In NestJS, I use it with TypeORM or Prisma, already designed that way, especially when the service must be tested without a database.

  • In Flutter, it's essential. The app shouldn't know whether data comes from the network or the local cache. The repository decides, the screen displays:

// domain/: the contract, with no technical dependency
abstract interface class OrderRepository {
  Future<List<Order>> getOrders();
}

// data/: the implementation, network first, cache as fallback
class OrderRepositoryImpl implements OrderRepository {
  OrderRepositoryImpl(this._api, this._cache);

  final OrdersApi _api;
  final OrdersCache _cache;

  @override
  Future<List<Order>> getOrders() async {
    try {
      final orders = await _api.fetchOrders();
      await _cache.save(orders);
      return orders;
    } on NetworkException {
      return _cache.load();
    }
  }
}

This domain / data split is at the heart of Clean Architecture with Flutter, the topic of the third article in the series.

Summary: where I find them

Pattern

Laravel

NestJS

Flutter

Singleton

$this->app->singleton()

Providers (default scope)

get_it, registerLazySingleton

Factory

Dedicated class + match

useFactory in a module

Dart factory constructors

Builder

Query Builder, Http client

TypeORM QueryBuilder

Widgets themselves

Adapter

One class per provider, bound in a provider

{ provide, useClass }

data layer

Decorator

Class wrapping a service

Class wrapping a service

Widgets wrapping others

Facade

Orchestrating service (mind the "Facades" name)

Orchestrating service

Domain use cases

Proxy

Eloquent lazy loading

ORM proxies

—

Strategy

Interface + implementations

Interface + providers

Interchangeable classes

Observer

Events and listeners

@nestjs/event-emitter

ChangeNotifier, Stream

Command

Jobs, Artisan commands

@nestjs/cqrs

—

State

Enums with transitions

Enums or state machine

Bloc states

Repository

Rarely (Active Record)

With TypeORM or Prisma

Essential

The trap: over-engineering

Patterns have three real qualities: a shared vocabulary ("let's use a strategy here" is understood in one sentence), code that's easier to evolve, and solutions proven over decades. But I've seen, and written, as much code damaged by too many patterns as by too few.

The signals that tell me a pattern is too much:

  • an interface with a single implementation, with no prospect of a second one nor need to fake it in tests;

  • a Factory that chooses nothing: it always creates the same class;

  • a Repository that copies the ORM method by method;

  • a Strategy for two cases that will never change: a simple if is more readable;

  • you need to open five files to understand what a button does.

My rule: I wait for the problem before applying the solution. The first switch stays a switch. At the third case, or as soon as it needs testing on its own, it becomes a strategy. A pattern is earned, not applied on principle.

Up next

Almost every example in this article actually applies the same small set of principles: one class, one responsibility; add without modifying; depend on interfaces rather than implementations. These are the SOLID principles, the topic of the next article in the series, built from real review comments.

Sources

Does this concern you? The service that answers itTechnical leadership

Share:

subscribe --blog

Get new posts by email

One email per new post, nothing else. Unsubscribe in one click.

Your address is only used to send you new posts. Privacy