يعني إيه؟
زي الفولدرات والملفات - تقدر تتعامل معاهم بنفس الطريقة! 📁
الفولدر جواه ملفات وفولدرات تانية - Tree Structure! 🌳
الـ Interface المشترك بين Leaf و Composite - كلهم عندهم getSize()!
الـ Objects البسيطة زي الملفات - مش بتحتوي على children!
الـ Container زي الفولدرات - فيها children وبتعمل delegate ليهم!
// 🧩 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
);
}
}
// 🌳 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