Programing/javascript

자바스크립트 Composite Pattern

Dongkkase 2025. 4. 19. 09:40
반응형

Composite Pattern(컴포지트 패턴) 은 객체들을 트리 구조로 구성하여 부분-전체 계층 구조를 동일하게 다룰 수 있도록 하는 구조 디자인 패턴입니다. 개별 객체와 그 객체들의 집합을 동일한 방식으로 처리할 수 있어 유연하고 확장성 높은 설계를 가능하게 합니다.


🧱 Composite Pattern이란?

Composite Pattern은 단일 객체와 복합 객체를 같은 방식으로 다룰 수 있게 하는 구조입니다. 부모-자식 관계가 있는 UI 트리 구조나 파일 시스템 등 계층 구조가 필요한 상황에서 자주 활용됩니다.

class Component {
    add(component) {}
    remove(component) {}
    display(indent = 0) {}
}

class Leaf extends Component {
    constructor(name) {
        super();
        this.name = name;
    }
    display(indent = 0) {
        console.log('-'.repeat(indent) + this.name);
    }
}

class Composite extends Component {
    constructor(name) {
        super();
        this.name = name;
        this.children = [];
    }
    add(component) {
        this.children.push(component);
    }
    remove(component) {
        this.children = this.children.filter(c => c !== component);
    }
    display(indent = 0) {
        console.log('-'.repeat(indent) + this.name);
        for (const child of this.children) {
            child.display(indent + 2);
        }
    }
}

const root = new Composite('root');
const branch1 = new Composite('branch1');
const branch2 = new Composite('branch2');
const leaf1 = new Leaf('leaf1');
const leaf2 = new Leaf('leaf2');

root.add(branch1);
root.add(branch2);
branch1.add(leaf1);
branch2.add(leaf2);

root.display();

✅ 장점

  1. 부분-전체를 일관된 방식으로 처리: 단일 객체와 복합 객체의 인터페이스 통일
  2. 확장성 우수: 새로운 요소나 그룹 추가가 유연함
  3. 재귀적 구조 표현에 유리: 트리 구조 표현에 적합

❌ 단점

  1. 구현 복잡도: 트리 구조로 인해 구조가 복잡해질 수 있음
  2. 불필요한 추상화 위험: 단순한 구조에도 과도한 계층이 생길 수 있음
  3. 디버깅 어려움: 중첩이 깊어질수록 추적이 어려움

🛠️ 실전 예시: 메뉴 시스템 구현

class MenuItem {
    constructor(name) {
        this.name = name;
    }
    display(indent = 0) {
        console.log('-'.repeat(indent) + this.name);
    }
}

class Menu {
    constructor(name) {
        this.name = name;
        this.items = [];
    }
    add(item) {
        this.items.push(item);
    }
    display(indent = 0) {
        console.log('-'.repeat(indent) + this.name);
        for (const item of this.items) {
            item.display(indent + 2);
        }
    }
}

const mainMenu = new Menu('Main Menu');
const fileMenu = new Menu('File');
const editMenu = new Menu('Edit');

fileMenu.add(new MenuItem('New'));
fileMenu.add(new MenuItem('Open'));
editMenu.add(new MenuItem('Cut'));
editMenu.add(new MenuItem('Paste'));

mainMenu.add(fileMenu);
mainMenu.add(editMenu);

mainMenu.display();

🧩 결론

Composite Pattern은 복잡한 트리 구조를 단순하게 표현하고 제어할 수 있는 강력한 패턴입니다. UI 구성 요소, 폴더/파일 구조, 메뉴 시스템 등 계층적 구조를 효과적으로 다루고자 할 때 매우 적합하며, 유지보수성과 재사용성 면에서도 뛰어난 설계 방식을 제공합니다.

반응형