CREATIONAL PATTERN

Builder Pattern

نمط البناء

يعني إيه؟ زي تجميع بيتزا - بتختار العجينة، الصوص، الجبنة، الإضافات! 🍕
بتبني الـ Object خطوة بخطوة مش مرة واحدة! 🔨

THE CONCEPT

مثال البيتزا 🍕

Builder = بناء Object معقد خطوة بخطوة! 🍕 new Builder() 🫓 .setDough() 🍅 .setSauce() 🧀 .setCheese() 🥬🍄 .addToppings() .build() → Pizza! 🍕 Final Pizza Object dough + sauce + cheese + toppings ✅ Method Chaining - كل method بترجع this! تقدر تبني Objects مختلفة بنفس الـ Builder!

🔨 Builder

الـ Class اللي فيه كل الـ set methods - كل method بترجع this عشان نقدر نعمل chaining!

🔗 Method Chaining

كل method return this - بنقدر نكتب الخطوات ورا بعض في سطر واحد!

🎯 build()

آخر method - بترجع الـ Object النهائي اللي اتبنى بكل الخطوات!

الكود 💻

Builder.js
class Pizza {
  constructor() {
    this.dough = null;
    this.sauce = null;
    this.cheese = null;
    this.toppings = [];
  }
}

class PizzaBuilder {
  constructor() {
    this.pizza = new Pizza();
  }
  
  // 🫓 كل method بترجع this!
  setDough(dough) {
    this.pizza.dough = dough;
    return this; // 👈 الـ Magic!
  }
  
  setSauce(sauce) {
    this.pizza.sauce = sauce;
    return this;
  }
  
  setCheese(cheese) {
    this.pizza.cheese = cheese;
    return this;
  }
  
  addTopping(topping) {
    this.pizza.toppings.push(topping);
    return this;
  }
  
  // 🎯 Build the final product!
  build() {
    return this.pizza;
  }
}
Usage.js
// 🍕 Method Chaining in action!
const pizza = new PizzaBuilder()
  .setDough('Thin Crust')      // 🫓
  .setSauce('Tomato')          // 🍅
  .setCheese('Mozzarella')     // 🧀
  .addTopping('Mushrooms')     // 🍄
  .addTopping('Olives')        // 🫒
  .addTopping('Pepperoni')     // 🍖
  .build();                    // 🎯

console.log(pizza);
// Pizza {
//   dough: 'Thin Crust',
//   sauce: 'Tomato', 
//   cheese: 'Mozzarella',
//   toppings: ['Mushrooms', 'Olives', 'Pepperoni']
// }

// 🍕 Easy to create different pizzas!
const veggiePizza = new PizzaBuilder()
  .setDough('Thick')
  .setSauce('Pesto')
  .setCheese('Vegan')
  .addTopping('Peppers')
  .build();

جرب! 🎮

🍕

ابني البيتزا بتاعتك!

// new PizzaBuilder()
Abstract Factory Prototype