Design Patterns

Pattern 12 sur 23, famille Structure

Proxy

En français : Procuration

Fournir un substitut qui contrôle l'accès à un objet : cache, chargement paresseux, sécurité, journalisation…

Le problème

Un service vidéo distant répond en 800 ms. Les mêmes vidéos sont demandées des milliers de fois et tu ne peux pas modifier le client tiers.

La solution

Créer un Proxy qui implémente la même interface que le service réel, intercepte les appels, ajoute sa logique (ici un cache) et ne délègue au service réel que si nécessaire.

Le pattern en action

  • Client
  • Rôle clé du pattern
  • Objet
  • Données ou état
  1. Le client croit parler au vrai service : même interface.
  2. Cache vide : le proxy délègue au service réel (≈ 800 ms).
  3. YouTubeApi (lent) → CachedVideoProxy : vidéo 42
  4. Le proxy mémorise le résultat.
  5. CachedVideoProxy → Client : vidéo 42
  6. Deuxième appel identique…
  7. CachedVideoProxy → cache {42} : get(42)
  8. cache {42} → CachedVideoProxy : hit !
  9. …servi depuis le cache : le service réel n'est pas sollicité.

Une analogie

Une carte bancaire : elle remplace l'argent liquide, et ajoute contrôles (code, plafond) avant de toucher au compte.

Quand l'utiliser

  • Cache / mémoïsation
  • Lazy loading (ORM, images lourdes)
  • Contrôle d'accès, rate limiting, logging
  • Objets distants (RPC, gRPC stubs)

Avantages et limites

Avantages

  • Transparent pour le client (même interface)
  • Ajoute du contrôle sans toucher au service
  • Open/Closed

Limites

  • Latence supplémentaire possible
  • Cohérence du cache à gérer (invalidation)

Implémentations

Le même exemple, écrit de façon idiomatique dans chaque langage.

Proxy en Python

proxy.py 28 lignes
import time
from typing import Protocol


class VideoService(Protocol):
    def get_video(self, vid: int) -> str: ...


class YouTubeApi:
    def get_video(self, vid: int) -> str:
        time.sleep(0.8)                      # appel réseau lent
        return f"video-{vid}"


class CachedVideoProxy:
    def __init__(self, real: VideoService):
        self._real = real
        self._cache: dict[int, str] = {}

    def get_video(self, vid: int) -> str:
        if vid not in self._cache:
            self._cache[vid] = self._real.get_video(vid)
        return self._cache[vid]


svc = CachedVideoProxy(YouTubeApi())
svc.get_video(42)   # lent
svc.get_video(42)   # instantané

Proxy en TypeScript

proxy.ts 23 lignes
interface VideoService {
  getVideo(id: number): Promise<string>;
}

class YouTubeApi implements VideoService {
  async getVideo(id: number) {
    const res = await fetch("https://api.example.com/videos/" + id);
    return res.text();
  }
}

class CachedVideoProxy implements VideoService {
  private cache = new Map<number, Promise<string>>();

  constructor(private real: VideoService) {}

  getVideo(id: number) {
    if (!this.cache.has(id)) this.cache.set(id, this.real.getVideo(id));
    return this.cache.get(id)!;
  }
}

// JS possède aussi un Proxy natif : new Proxy(target, { get(t, key) { … } })

Proxy en Java

proxy.java 21 lignes
interface VideoService { String getVideo(int id); }

class YouTubeApi implements VideoService {
    public String getVideo(int id) {
        /* appel HTTP lent */
        return "video-" + id;
    }
}

class CachedVideoProxy implements VideoService {
    private final VideoService real;
    private final Map<Integer, String> cache = new ConcurrentHashMap<>();

    CachedVideoProxy(VideoService real) { this.real = real; }

    public String getVideo(int id) {
        return cache.computeIfAbsent(id, real::getVideo);
    }
}

// Spring (@Transactional, @Cacheable) repose sur des proxys dynamiques

Proxy en C#

proxy.cs 13 lignes
interface IVideoService { Task<string> GetVideoAsync(int id); }

class YouTubeApi(HttpClient http) : IVideoService
{
    public Task<string> GetVideoAsync(int id) => http.GetStringAsync($"/videos/{id}");
}

class CachedVideoProxy(IVideoService real) : IVideoService
{
    private readonly ConcurrentDictionary<int, Task<string>> _cache = new();

    public Task<string> GetVideoAsync(int id) => _cache.GetOrAdd(id, real.GetVideoAsync);
}

Proxy en PHP

proxy.php 24 lignes
interface VideoService { public function getVideo(int $id): string; }

final class YouTubeApi implements VideoService
{
    public function getVideo(int $id): string
    {
        usleep(800_000);              // appel lent
        return "video-$id";
    }
}

final class CachedVideoProxy implements VideoService
{
    private array $cache = [];

    public function __construct(private VideoService $real) {}

    public function getVideo(int $id): string
    {
        return $this->cache[$id] ??= $this->real->getVideo($id);
    }
}

// Doctrine / Eloquent utilisent des proxys pour le lazy-loading des relations

Proxy en Go

proxy.go 26 lignes
type VideoService interface {
    GetVideo(id int) (string, error)
}

type CachedVideoProxy struct {
    real  VideoService
    mu    sync.RWMutex
    cache map[int]string
}

func (p *CachedVideoProxy) GetVideo(id int) (string, error) {
    p.mu.RLock()
    v, ok := p.cache[id]
    p.mu.RUnlock()
    if ok {
        return v, nil
    }
    v, err := p.real.GetVideo(id)
    if err != nil {
        return "", err
    }
    p.mu.Lock()
    p.cache[id] = v
    p.mu.Unlock()
    return v, nil
}

Questions fréquentes

Qu'est-ce que le design pattern Proxy ?

Fournir un substitut qui contrôle l'accès à un objet : cache, chargement paresseux, sécurité, journalisation… Créer un Proxy qui implémente la même interface que le service réel, intercepte les appels, ajoute sa logique (ici un cache) et ne délègue au service réel que si nécessaire.

Quand utiliser le pattern Proxy ?

Cache / mémoïsation ; Lazy loading (ORM, images lourdes) ; Contrôle d'accès, rate limiting, logging ; Objets distants (RPC, gRPC stubs).

Quels sont les avantages et les inconvénients du pattern Proxy ?

Avantages : Transparent pour le client (même interface) ; Ajoute du contrôle sans toucher au service ; Open/Closed. Limites : Latence supplémentaire possible ; Cohérence du cache à gérer (invalidation).