Builder
En français : Monteur
Construire un objet complexe étape par étape, en séparant sa construction de sa représentation.
- 7 étapes animées
- 6 langages
- Patterns de création
Le problème
Un objet HttpRequest a une dizaine de paramètres optionnels. Le constructeur « télescopique » new HttpRequest(url, null, null, true, null…) devient illisible et fragile.
La solution
Extraire la construction dans un objet Builder doté de méthodes chaînables (method(), header(), body()), puis d'un build() final qui valide et produit un objet complet, souvent immuable.
Le pattern en action
- Client
- Rôle clé du pattern
- Objet
- Données ou état
- Le client démarre avec le strict nécessaire.
- Chaque appel ajoute une étape et renvoie le builder (chaînage).
- Client → RequestBuilder {url, POST} : .header(...)
- L'ordre et le choix des étapes sont libres.
- Le client déclenche la construction finale.
- Le builder valide puis produit un objet complet et immuable.
- Le client récupère un objet prêt à l'emploi.
Une analogie
Commander un sandwich au comptoir : pain, puis garniture, puis sauce… et on ne te le remet qu'une fois terminé.
Quand l'utiliser
- Objets avec beaucoup de paramètres optionnels
- Objets immuables à construire progressivement
- Query builders, requêtes HTTP, configurations, tests (fixtures)
Avantages et limites
Avantages
- Code client lisible et auto-documenté
- Validation centralisée dans build()
- Produit immuable et toujours cohérent
Limites
- Classe supplémentaire à maintenir
- Verbeux pour des objets simples (préférer les paramètres nommés)
Implémentations
Le même exemple, écrit de façon idiomatique dans chaque langage.
Builder en Python
from dataclasses import dataclass
@dataclass(frozen=True)
class HttpRequest:
url: str
method: str
headers: dict
body: str | None
class RequestBuilder:
def __init__(self, url: str):
self._url, self._method = url, "GET"
self._headers: dict[str, str] = {}
self._body: str | None = None
def method(self, m: str):
self._method = m
return self
def header(self, k: str, v: str):
self._headers[k] = v
return self
def body(self, b: str):
self._body = b
return self
def build(self) -> HttpRequest:
if self._method == "GET" and self._body:
raise ValueError("GET sans body")
return HttpRequest(self._url, self._method, dict(self._headers), self._body)
req = (RequestBuilder("/api/users")
.method("POST")
.header("Content-Type", "application/json")
.body('{"name": "Ali"}')
.build())
Builder en TypeScript
class HttpRequest {
constructor(
readonly url: string,
readonly method: string,
readonly headers: Readonly<Record<string, string>>,
readonly body?: string,
) {}
}
class RequestBuilder {
private _method = "GET";
private _headers: Record<string, string> = {};
private _body?: string;
constructor(private url: string) {}
method(m: string) { this._method = m; return this; }
header(k: string, v: string) { this._headers[k] = v; return this; }
body(b: string) { this._body = b; return this; }
build() {
return new HttpRequest(this.url, this._method, { ...this._headers }, this._body);
}
}
const req = new RequestBuilder("/api/users")
.method("POST")
.header("Content-Type", "application/json")
.body(JSON.stringify({ name: "Ali" }))
.build();
Builder en Java
public final class HttpRequest {
private final String url, method, body;
private final Map<String, String> headers;
private HttpRequest(Builder b) {
url = b.url; method = b.method; body = b.body;
headers = Map.copyOf(b.headers);
}
public static class Builder {
private final String url;
private String method = "GET", body;
private final Map<String, String> headers = new HashMap<>();
public Builder(String url) { this.url = url; }
public Builder method(String m) { method = m; return this; }
public Builder header(String k, String v) { headers.put(k, v); return this; }
public Builder body(String b) { body = b; return this; }
public HttpRequest build() { return new HttpRequest(this); }
}
}
HttpRequest req = new HttpRequest.Builder("/api/users")
.method("POST")
.header("Content-Type", "application/json")
.build();
// Lombok : @Builder génère tout cela automatiquement
Builder en C#
public record HttpRequest(
string Url, string Method,
IReadOnlyDictionary<string, string> Headers, string? Body);
public class RequestBuilder(string url)
{
private string _method = "GET";
private string? _body;
private readonly Dictionary<string, string> _headers = new();
public RequestBuilder Method(string m) { _method = m; return this; }
public RequestBuilder Header(string k, string v) { _headers[k] = v; return this; }
public RequestBuilder Body(string b) { _body = b; return this; }
public HttpRequest Build() =>
new(url, _method, new Dictionary<string, string>(_headers), _body);
}
var req = new RequestBuilder("/api/users")
.Method("POST")
.Header("Content-Type", "application/json")
.Body("{}")
.Build();
Builder en PHP
final class HttpRequest
{
public function __construct(
public readonly string $url,
public readonly string $method,
public readonly array $headers,
public readonly ?string $body,
) {}
}
final class RequestBuilder
{
private string $method = 'GET';
private array $headers = [];
private ?string $body = null;
public function __construct(private string $url) {}
public function method(string $m): static { $this->method = $m; return $this; }
public function header(string $k, string $v): static { $this->headers[$k] = $v; return $this; }
public function body(string $b): static { $this->body = $b; return $this; }
public function build(): HttpRequest
{
return new HttpRequest($this->url, $this->method, $this->headers, $this->body);
}
}
$req = (new RequestBuilder('/api/users'))->method('POST')->body('{}')->build();
// Laravel : le Query Builder (DB::table()->where()->orderBy()->get()) suit ce principe
Builder en Go
type HttpRequest struct {
URL, Method, Body string
Headers map[string]string
}
type Option func(*HttpRequest)
func Method(m string) Option { return func(r *HttpRequest) { r.Method = m } }
func Header(k, v string) Option { return func(r *HttpRequest) { r.Headers[k] = v } }
func Body(b string) Option { return func(r *HttpRequest) { r.Body = b } }
// Variante idiomatique Go du Builder : les "functional options"
func NewRequest(url string, opts ...Option) *HttpRequest {
r := &HttpRequest{URL: url, Method: "GET", Headers: map[string]string{}}
for _, o := range opts {
o(r)
}
return r
}
req := NewRequest("/api/users",
Method("POST"),
Header("Content-Type", "application/json"),
)
Questions fréquentes
Qu'est-ce que le design pattern Builder ?
Construire un objet complexe étape par étape, en séparant sa construction de sa représentation. Extraire la construction dans un objet Builder doté de méthodes chaînables (method(), header(), body()), puis d'un build() final qui valide et produit un objet complet, souvent immuable.
Quand utiliser le pattern Builder ?
Objets avec beaucoup de paramètres optionnels ; Objets immuables à construire progressivement ; Query builders, requêtes HTTP, configurations, tests (fixtures).
Quels sont les avantages et les inconvénients du pattern Builder ?
Avantages : Code client lisible et auto-documenté ; Validation centralisée dans build() ; Produit immuable et toujours cohérent. Limites : Classe supplémentaire à maintenir ; Verbeux pour des objets simples (préférer les paramètres nommés).