CREATIONAL PATTERN

Prototype Pattern

نمط الاستنساخ

يعني إيه؟ زي النسخ واللصق في البرامج! 📋
بدل ما تعمل Object جديد من الصفر - انسخ واحد موجود! 🧬

THE CONCEPT

مثال استنساخ الخلايا 🧬

Prototype = clone() بدل new! 🧬 Original Prototype color: "blue" size: 100 .clone() .clone() .clone() 🧬 Clone 1 (blue) 🧬 Clone 2 (purple) 🧬 Clone 3 (green) ❌ new Object() - Expensive! كل مرة نعمل Object جديد من الصفر - وقت كتير! ✅ clone() - Fast! ننسخ Object موجود ونغير اللي محتاجينه بس! 🧬 Clone = Deep Copy + Customize!

🧬 Prototype

الـ Object الأصلي اللي عنده method clone() - بيعرف ينسخ نفسه!

📋 clone()

الـ Method اللي بتعمل نسخة كاملة من الـ Object - Deep Copy مش Reference!

⚡ Performance

أسرع من new خصوصاً لو الـ Object معقد ومحتاج setup كتير!

الكود 💻

Prototype.js
class Shape {
  constructor(color, x, y) {
    this.color = color;
    this.x = x;
    this.y = y;
  }
  
  // 🧬 Clone method - Deep Copy!
  clone() {
    // Object.assign for shallow copy
    // For nested objects, use structuredClone()
    return Object.assign(
      Object.create(Object.getPrototypeOf(this)),
      this
    );
  }
  
  draw() {
    return `Drawing ${this.color} shape at (${this.x}, ${this.y})`;
  }
}

class Circle extends Shape {
  constructor(color, x, y, radius) {
    super(color, x, y);
    this.radius = radius;
  }
  
  draw() {
    return `⭕ ${this.color} circle r=${this.radius} at (${this.x}, ${this.y})`;
  }
}
Usage.js
// 🎯 Create original prototype
const blueCircle = new Circle('blue', 10, 20, 50);
console.log(blueCircle.draw());
// ⭕ blue circle r=50 at (10, 20)

// 🧬 Clone instead of new!
const redCircle = blueCircle.clone();
redCircle.color = 'red';  // Just change what you need!
redCircle.x = 100;

console.log(redCircle.draw());
// ⭕ red circle r=50 at (100, 20)

// ✅ They are separate objects!
console.log(blueCircle === redCircle); // false

// 🚀 Useful for expensive objects
const expensiveObject = {
  data: loadFromDatabase(), // Expensive!
  cache: buildCache(),      // Expensive!
  config: parseConfig()     // Expensive!
};

// Just clone when you need another one!
const copy = Object.assign({}, expensiveObject);

جرب! 🎮

🔵

الشكل الأصلي - اضغط Clone!

// Original: blueCircle = new Circle('blue', 10, 20, 50)

امتى نستخدمه؟ 🤔

🎮

Game Objects

bullets, enemies, particles - بنعمل clone بدل new!

📊

Complex Configurations

إعدادات معقدة - ننسخها ونعدل الفرق بس!

🗄️

Database Records

Records متشابهة - clone أسرع من query جديد!

🎨

UI Components

Components متشابهة - ننسخها بدل ما نبنيها!

Builder Singleton