Builder is a creational design pattern that lets you construct complex objects step by step. Unlike other creational patterns like Singleton Pattern or Factory Method Pattern, Builder does not require products to share a common interface.
Purpose and Use Case
Use the Builder pattern when you need to construct objects with many optional parameters, avoid the Telescoping ConstructorGlosarioTelescoping Constructor (Constructor Telescópico)Antipatrón de diseño en POO que ocurre cuando una clase define múltiples constructores sobrecargados con listas de parámetros progresivamente más largas para manejar argumentos opcionales. Produce código rígido, difícil de mantener y propenso a errores al invocar.Ver término completo → anti-pattern, and apply clean design principles like SOLIDGlosarioSOLIDAcrónimo de cinco principios de diseño orientado a objetos y programación diseñados para hacer que el software sea más comprensible, flexible y mantenible: S - Single Responsibility Principle (Responsabilidad Única) O - Open/Closed Principle (Abierto/Cerrado) L - Liskov Substitution Principle (Sustitución de Liskov) I - Interface Segregation Principle (Segregación de Interfaz) D - Dependency Inversion Principle (Inversión de Dependencias) Ver término completo → and KISSGlosarioKISS (Keep It Simple, Stupid)Principio de diseño que establece que la mayoría de los sistemas funcionan mejor si se mantienen simples en lugar de hacerlos complejos. Se debe evitar la complejidad innecesaria en la arquitectura y el código.Ver término completo →.
Pattern Structure
- Builder (Interface): Declares construction steps common to all builder types.
- Concrete Builder: Provides different implementations of construction steps and assembles the final product.
- Product: The resulting complex object created.
- Director (Optional): Defines the order in which construction steps should be called to reuse specific configurations.
Execution Flow
- Invocation: Client creates an instance of the Builder or calls the Director.
- Chaining (Fluent Interface): Configuration methods that return
thisare executed sequentially. - Construction: The
build()method validates required fields and returns the final configured complex object.
Real Implementation Examples
// QueryBuilder.ts — Fluent SQL/Database Query Builder
class SQLQueryBuilder {
private query: {
table: string;
fields: string[];
whereConditions: string[];
limitCount?: number;
} = { table: '', fields: [], whereConditions: [] };
public select(fields: string[]): this {
this.query.fields = fields;
return this;
}
public from(table: string): this {
this.query.table = table;
return this;
}
public where(condition: string): this {
this.query.whereConditions.push(condition);
return this;
}
public limit(count: number): this {
this.query.limitCount = count;
return this;
}
public build(): string {
if (!this.query.table) {
throw new Error("Table must be specified using .from()");
}
const fieldsStr = this.query.fields.length ? this.query.fields.join(", ") : "*";
let sql = `SELECT ${fieldsStr} FROM ${this.query.table}`;
if (this.query.whereConditions.length) {
sql += ` WHERE ${this.query.whereConditions.join(" AND ")}`;
}
if (this.query.limitCount) {
sql += ` LIMIT ${this.query.limitCount}`;
}
return sql;
}
}
// Practical usage:
const query = new SQLQueryBuilder()
.select(["id", "name", "email"])
.from("users")
.where("status = 'active'")
.limit(10)
.build();
console.log(query); // SELECT id, name, email FROM users WHERE status = 'active' LIMIT 10