sdfxs

Untitled

Jun 15th, 2021
908
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. abstract class Component {
  2.     protected parent: Component | null = null;
  3.     public setParent(parent: Component | null) {
  4.         this.parent = parent;
  5.     }
  6.     public getParent(): Component | null {
  7.         return this.parent;
  8.     }
  9.     public add(component: Component): void { }
  10.     public remove(component: Component): void { }
  11.     public isComposite(): boolean {
  12.         return false;
  13.     }
  14.     public abstract operation(): string;
  15. }
  16.  
  17. class Leaf extends Component {
  18.     public operation(): string {
  19.         return 'Лист';
  20.     }
  21. }
  22.  
  23. class Composite extends Component {
  24.     protected children: Component[] = [];
  25.  
  26.     public add(component: Component): void {
  27.         this.children.push(component);
  28.         component.setParent(this);
  29.     }
  30.  
  31.     public remove(component: Component): void {
  32.         const componentIndex = this.children.indexOf(component);
  33.         this.children.splice(componentIndex, 1);
  34.  
  35.         component.setParent(null);
  36.     }
  37.  
  38.     public isComposite(): boolean {
  39.         return true;
  40.     }
  41.  
  42.     public operation(): string {
  43.         const results = [];
  44.         for (const child of this.children) {
  45.             results.push(child.operation());
  46.         }
  47.  
  48.         return `Ветка(${results.join('+')})`;
  49.     }
  50. }
  51.  
  52. const tree = new Composite();
  53. const branch1 = new Composite();
  54. branch1.add(new Leaf());
  55. branch1.add(new Leaf());
  56. const branch2 = new Composite();
  57. branch2.add(new Leaf());
  58. tree.add(branch1);
  59. tree.add(branch2);
  60.  
  61. console.log(tree.operation());
RAW Paste Data