Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Component interface
- interface FileSystemComponent {
- name: string;
- open(): void;
- }
- // Leaf Node
- class File implements FileSystemComponent {
- constructor(public name: string) {}
- open() {
- console.log(`Opening the file ${this.name}`);
- }
- }
- // Composite Node
- class Folder implements FileSystemComponent {
- name: string;
- children: FileSystemComponent[] = [];
- constructor(name: string) {
- this.name = name;
- }
- add(child: FileSystemComponent): void {
- this.children.push(child);
- }
- open() {
- console.log(`Opening the folder ${this.name}`);
- this.children.forEach(child => child.open());
- }
- }
- // Usage
- const file1 = new File("file1.txt");
- const file2 = new File("file2.txt");
- const folder1 = new Folder("folder1");
- // Adding files to folder1
- folder1.add(file1);
- folder1.add(file2);
- // Create another folder and add folder1 to it
- const folder2 = new Folder("folder2");
- const file3 = new File("file3.txt");
- folder2.add(file3);
- folder2.add(folder1);
- // Now open all files in folder2. This should also open all files in folder1
- folder2.open();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement