// Component interface
interface FileSystemNode {
getName(): string;
getSize(): number;
print(): void;
}
// Leaf class for files
class File implements FileSystemNode {
constructor(private name: string, private size: number) {}
getName() {
return this.name;
}
getSize() {
return this.size;
}
print() {
console.log(`File: ${this.getName()} (${this.getSize()} bytes)`);
}
}
// Composite class for folders
class Folder implements FileSystemNode {
private children: FileSystemNode[] = [];
constructor(private name: string) {}
getName() {
return this.name;
}
getSize() {
let totalSize = 0;
for (const child of this.children) {
totalSize += child.getSize();
}
return totalSize;
}
print() {
console.log(`Folder: ${this.getName()} (${this.getSize()} bytes)`);
for (const child of this.children) {
child.print();
}
}
addChild(child: FileSystemNode) {
this.children.push(child);
}
removeChild(child: FileSystemNode) {
const index = this.children.indexOf(child);
if (index > -1) {
this.children.splice(index, 1);
}
}
}
// Use the composite pattern to create a file system hierarchy
const file1 = new File("file1.txt", 100);
const file2 = new File("file2.txt", 200);
const file3 = new File("file3.txt", 300);
const folder1 = new Folder("folder1");
const folder2 = new Folder("folder2");
folder1.addChild(file1);
folder1.addChild(file2);
folder2.addChild(file3);
folder2.addChild(folder1);
folder2.print();