STRUCTURAL PATTERN

Composite Pattern

نمط التركيب

يعني إيه؟ زي الفولدرات والملفات - تقدر تتعامل معاهم بنفس الطريقة! 📁
الفولدر جواه ملفات وفولدرات تانية - Tree Structure! 🌳

THE CONCEPT

مثال الفولدرات 📁

Composite = Tree of Objects! 📁 Root 📁 Documents 📁 Images 📄 report.txt 📄 notes.txt 🖼️ photo.jpg 🖼️ logo.png ✅ Same Interface! 📁 folder.getSize() = sum of children 📄 file.getSize() = actual file size كلهم Component - نتعامل معاهم بنفس الطريقة!

🧩 Component

الـ Interface المشترك بين Leaf و Composite - كلهم عندهم getSize()!

📄 Leaf

الـ Objects البسيطة زي الملفات - مش بتحتوي على children!

📁 Composite

الـ Container زي الفولدرات - فيها children وبتعمل delegate ليهم!

الكود 💻

Composite.js
// 🧩 Component Interface
class FileSystemItem {
  getSize() { throw "implement!"; }
  getName() { throw "implement!"; }
}

// 📄 Leaf - الملف
class File extends FileSystemItem {
  constructor(name, size) {
    super();
    this.name = name;
    this.size = size;
  }
  getName() { return `📄 ${this.name}`; }
  getSize() { return this.size; }
}

// 📁 Composite - الفولدر
class Folder extends FileSystemItem {
  constructor(name) {
    super();
    this.name = name;
    this.children = []; // 👈 Contains other Components!
  }
  
  add(item) { this.children.push(item); }
  remove(item) { 
    this.children = this.children.filter(c => c !== item);
  }
  
  getName() { return `📁 ${this.name}`; }
  
  // 🔄 Recursive - بيجمع من كل الـ children!
  getSize() {
    return this.children.reduce(
      (sum, child) => sum + child.getSize(), 
      0
    );
  }
}
Usage.js
// 🌳 Build the tree
const root = new Folder("Root");
const docs = new Folder("Documents");
const images = new Folder("Images");

docs.add(new File("report.txt", 100));
docs.add(new File("notes.txt", 50));

images.add(new File("photo.jpg", 500));
images.add(new File("logo.png", 200));

root.add(docs);
root.add(images);

// 🎯 Same interface for all!
console.log(root.getSize());   // 850 (sum of all!)
console.log(docs.getSize());   // 150
console.log(images.getSize()); // 700

// ✅ نتعامل مع Folder و File بنفس الطريقة!
function printSize(item) {
  console.log(`${item.getName()}: ${item.getSize()} bytes`);
}
printSize(root);   // 📁 Root: 850 bytes
printSize(docs);   // 📁 Documents: 150 bytes

جرب! 🎮

📁 Root (0 bytes)
// Build your file tree!
Bridge Decorator