# 컴포지트 패턴

---

컴포지트 패턴은 주로 계층구조에서 사용되며, 개별 개체와 개체 그룹 모두를 일관된 인터페이스로 작업할 때 유용하다. 폴더 - 파일 트리의 관계를 생각해보자.

```
// 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();
```

For the site tree, see the [root Markdown](https://slashpage.com/develop.md).
