يعني إيه؟
زي تجميع بيتزا - بتختار العجينة، الصوص، الجبنة، الإضافات! 🍕
بتبني الـ Object خطوة بخطوة مش مرة واحدة! 🔨
الـ Class اللي فيه كل الـ set methods -
كل method بترجع this عشان نقدر نعمل chaining!
كل method return this - بنقدر نكتب الخطوات ورا بعض في سطر واحد!
آخر method - بترجع الـ Object النهائي اللي اتبنى بكل الخطوات!
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;
}
}
// 🍕 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();
ابني البيتزا بتاعتك!