Advertisement
Idanref

Composite Example

Sep 25th, 2023
978
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Component interface
  2. interface FileSystemComponent {
  3.   name: string;
  4.   open(): void;
  5. }
  6.  
  7. // Leaf Node
  8. class File implements FileSystemComponent {
  9.   constructor(public name: string) {}
  10.  
  11.   open() {
  12.     console.log(`Opening the file ${this.name}`);
  13.   }
  14. }
  15.  
  16. // Composite Node
  17. class Folder implements FileSystemComponent {
  18.   name: string;
  19.   children: FileSystemComponent[] = [];
  20.  
  21.   constructor(name: string) {
  22.     this.name = name;
  23.   }
  24.  
  25.   add(child: FileSystemComponent): void {
  26.     this.children.push(child);
  27.   }
  28.  
  29.   open() {
  30.     console.log(`Opening the folder ${this.name}`);
  31.     this.children.forEach(child => child.open());
  32.   }
  33. }
  34.  
  35. // Usage
  36. const file1 = new File("file1.txt");
  37. const file2 = new File("file2.txt");
  38. const folder1 = new Folder("folder1");
  39.  
  40. // Adding files to folder1
  41. folder1.add(file1);
  42. folder1.add(file2);
  43.  
  44. // Create another folder and add folder1 to it
  45. const folder2 = new Folder("folder2");
  46. const file3 = new File("file3.txt");
  47. folder2.add(file3);
  48. folder2.add(folder1);
  49.  
  50. // Now open all files in folder2. This should also open all files in folder1
  51. folder2.open();
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement