STRUCTURAL PATTERN

Flyweight Pattern

نمط الوزن الخفيف

يعني إيه؟ زي الحروف في Word - مش كل "A" object جديد! 🔤
بنشارك الـ Common Data عشان نوفر Memory! 💾

مثال الـ Trees 🌳

🪶 Flyweight

الـ Object اللي فيه Intrinsic State المشترك - زي mesh و texture!

🎨 Intrinsic

الـ Data الثابتة اللي مش بتتغير - تتشارك!

📍 Extrinsic

الـ Data المتغيرة لكل Object - زي x, y!

الكود 💻

Flyweight.js
// 🪶 Flyweight - Shared intrinsic state
class TreeType {
  constructor(name, color, texture) {
    this.name = name;
    this.color = color;
    this.texture = texture; // 🎨 Heavy!
  }
}

// 🏭 Factory - Cache & Reuse!
class TreeFactory {
  static types = {};
  
  static getTreeType(name, color, texture) {
    const key = `${name}-${color}`;
    if (!this.types[key]) {
      this.types[key] = new TreeType(name, color, texture);
    }
    return this.types[key];
  }
}

// 🌲 Context - Extrinsic state
class Tree {
  constructor(x, y, type) {
    this.x = x;       // 📍 Unique per tree
    this.y = y;       // 📍 Unique per tree
    this.type = type; // 🪶 Shared reference!
  }
}

// ✅ 1000 trees, only 2 types in memory!

جرب! 🎮

0

🌳 Total Trees

0

🪶 Shared Types

// TreeFactory ready!
Facade Proxy