Separates the construction of a complex object from its representation, allowing the same construction process to create different representations.
Useful when an object has many optional parameters.
class Pizza {
final String size;
final bool cheese;
final bool pepperoni;
Pizza._({required this.size, this.cheese = false, this.pepperoni = false});
}
class PizzaBuilder {
String _size = 'medium';
bool _cheese = false;
bool _pepperoni = false;
PizzaBuilder size(String size) { _size = size; return this; }
PizzaBuilder addCheese() { _cheese = true; return this; }
PizzaBuilder addPepperoni() { _pepperoni = true; return this; }
Pizza build() => Pizza._(size: _size, cheese: _cheese, pepperoni: _pepperoni);
}
// Usage
final pizza = PizzaBuilder().size('large').addCheese().addPepperoni().build();