본문으로 건너뛰기
Previous
Next
C++ Composite 패턴 완벽 가이드 | 트리 구조를 동일 인터페이스로 다루기

C++ Composite 패턴 완벽 가이드 | 트리 구조를 동일 인터페이스로 다루기

C++ Composite 패턴 완벽 가이드 | 트리 구조를 동일 인터페이스로 다루기

이 글의 핵심

C++ Composite 패턴 : 트리 구조를 동일 인터페이스로 다루기. Composite 패턴이란?. 왜 필요한가·기본 구조.

Composite 패턴이란? 왜 필요한가

트리·부분-전체를 한 인터페이스로 묶는 흐름은 구조 패턴 시리즈의 다른 패턴들과 비교해 읽으면 좋습니다.

문제 시나리오: 개별 객체와 그룹을 다르게 처리

문제: 파일과 폴더를 다른 방식으로 처리하면 코드가 복잡해집니다.

// 나쁜 설계: 타입 체크 필요
void printSize(FileSystemItem* item) {
    if (auto* file = dynamic_cast<File*>(item)) {
        std::cout << file->getSize() << '\n';
    } else if (auto* folder = dynamic_cast<Folder*>(item)) {
        for (auto& child : folder->getChildren()) {
            printSize(child);  // 재귀
        }
    }
}

해결: Composite 패턴leaf(파일)와 composite(폴더)를 동일한 인터페이스로 다룹니다.

// 좋은 설계: Composite
// 타입 정의
class Component {
public:
    virtual int getSize() const = 0;  // 통일된 인터페이스
};
class File : public Component {
    int size_;
public:
    int getSize() const override { return size_; }
};
class Folder : public Component {
    std::vector<std::shared_ptr<Component>> children_;
public:
    int getSize() const override {
        int total = 0;
        for (const auto& child : children_)
            total += child->getSize();  // 재귀
        return total;
    }
};
flowchart TD
    client[Client]
    component[Componentbr/(getSize)]
    leaf[Leafbr/(File)]
    composite[Compositebr/(Folder)]
    
    client --> component
    leaf -.implements.-> component
    composite -.implements.-> component
    composite --> component

1. 기본 구조

#include <vector>
#include <memory>
#include <iostream>
class Component {
public:
    virtual void operation() const = 0;
    virtual void add(std::shared_ptr<Component>) {}
    virtual void remove(std::shared_ptr<Component>) {}
    virtual ~Component() = default;
};
// Leaf: 자식 없음
class Leaf : public Component {
    int id_;
public:
    explicit Leaf(int id) : id_(id) {}
    void operation() const override {
        std::cout << "Leaf " << id_ << '\n';
    }
};
// Composite: 자식 목록 보유
class Composite : public Component {
    std::vector<std::shared_ptr<Component>> children_;
public:
    void add(std::shared_ptr<Component> c) override {
        children_.push_back(std::move(c));
    }
    void remove(std::shared_ptr<Component> c) override {
        children_.erase(
            std::remove(children_.begin(), children_.end(), c),
            children_.end()
        );
    }
    void operation() const override {
        std::cout << "Composite [\n";
        for (const auto& c : children_)
            c->operation();
        std::cout << "]\n";
    }
};
int main() {
    auto root = std::make_shared<Composite>();
    root->add(std::make_shared<Leaf>(1));
    
    auto branch = std::make_shared<Composite>();
    branch->add(std::make_shared<Leaf>(2));
    branch->add(std::make_shared<Leaf>(3));
    root->add(branch);
    
    root->operation();
    // 출력:
    // Composite [
    // Leaf 1
    // Composite [
    // Leaf 2
    // Leaf 3
    // ]
    // ]
    return 0;
}

2. 파일 시스템 예제

파일과 폴더의 크기 계산

#include <vector>
#include <memory>
#include <iostream>
#include <string>
class FileSystemItem {
public:
    virtual int getSize() const = 0;
    virtual void print(int indent = 0) const = 0;
    virtual ~FileSystemItem() = default;
};
class File : public FileSystemItem {
    std::string name_;
    int size_;
public:
    File(std::string name, int size) : name_(std::move(name)), size_(size) {}
    
    int getSize() const override { return size_; }
    
    void print(int indent = 0) const override {
        std::cout << std::string(indent, ' ') << "File: " << name_ 
                  << " (" << size_ << " bytes)\n";
    }
};
class Folder : public FileSystemItem {
    std::string name_;
    std::vector<std::shared_ptr<FileSystemItem>> children_;
public:
    explicit Folder(std::string name) : name_(std::move(name)) {}
    
    void add(std::shared_ptr<FileSystemItem> item) {
        children_.push_back(std::move(item));
    }
    
    int getSize() const override {
        int total = 0;
        for (const auto& child : children_)
            total += child->getSize();
        return total;
    }
    
    void print(int indent = 0) const override {
        std::cout << std::string(indent, ' ') << "Folder: " << name_ 
                  << " (" << getSize() << " bytes total)\n";
        for (const auto& child : children_)
            child->print(indent + 2);
    }
};
int main() {
    auto root = std::make_shared<Folder>("root");
    root->add(std::make_shared<File>("readme.txt", 100));
    
    auto src = std::make_shared<Folder>("src");
    src->add(std::make_shared<File>("main.cpp", 500));
    src->add(std::make_shared<File>("utils.cpp", 300));
    root->add(src);
    
    auto docs = std::make_shared<Folder>("docs");
    docs->add(std::make_shared<File>("manual.pdf", 2000));
    root->add(docs);
    
    root->print();
    // 출력:
    // Folder: root (2900 bytes total)
    //   File: readme.txt (100 bytes)
    //   Folder: src (800 bytes total)
    //     File: main.cpp (500 bytes)
    //     File: utils.cpp (300 bytes)
    //   Folder: docs (2000 bytes total)
    //     File: manual.pdf (2000 bytes)
    
    return 0;
}

핵심: getSize()가 재귀적으로 호출되어 전체 트리의 크기를 계산합니다.

3. UI 컴포넌트 계층

GUI 위젯 트리

#include <vector>
#include <memory>
#include <iostream>
#include <string>
class Widget {
public:
    virtual void render() const = 0;
    virtual void add(std::shared_ptr<Widget>) {}
    virtual ~Widget() = default;
};
class Button : public Widget {
    std::string label_;
public:
    explicit Button(std::string label) : label_(std::move(label)) {}
    
    void render() const override {
        std::cout << "[Button: " << label_ << "]\n";
    }
};
class Label : public Widget {
    std::string text_;
public:
    explicit Label(std::string text) : text_(std::move(text)) {}
    
    void render() const override {
        std::cout << "Label: " << text_ << '\n';
    }
};
class Panel : public Widget {
    std::string title_;
    std::vector<std::shared_ptr<Widget>> children_;
public:
    explicit Panel(std::string title) : title_(std::move(title)) {}
    
    void add(std::shared_ptr<Widget> widget) override {
        children_.push_back(std::move(widget));
    }
    
    void render() const override {
        std::cout << "=== Panel: " << title_ << " ===\n";
        for (const auto& child : children_)
            child->render();
        std::cout << "===================\n";
    }
};
int main() {
    auto mainPanel = std::make_shared<Panel>("Main Window");
    mainPanel->add(std::make_shared<Label>("Welcome!"));
    
    auto buttonPanel = std::make_shared<Panel>("Actions");
    buttonPanel->add(std::make_shared<Button>("OK"));
    buttonPanel->add(std::make_shared<Button>("Cancel"));
    mainPanel->add(buttonPanel);
    
    mainPanel->render();
    // 출력:
    // === Panel: Main Window ===
    // Label: Welcome!
    // === Panel: Actions ===
    // [Button: OK]
    // [Button: Cancel]
    // ===================
    // ===================
    
    return 0;
}

핵심: Panel은 다른 Panel이나 Button을 포함할 수 있어 중첩된 UI 계층을 표현합니다.

4. 자주 발생하는 문제와 해결법

문제 1: Leaf에 add() 호출

// ❌ 나쁜 예: Leaf에 add() 호출 시 무시됨
auto file = std::make_shared<File>("test.txt", 100);
file->add(anotherFile);  // 아무 일도 안 일어남

해결: Leaf의 add()에서 예외를 던지거나, 타입 체크를 추가하세요.

// ✅ 좋은 예: 예외 던지기
class File : public FileSystemItem {
public:
    void add(std::shared_ptr<FileSystemItem>) override {
        throw std::logic_error("Cannot add to a file");
    }
};

문제 2: 순환 참조

// ❌ 나쁜 예: 순환 참조
auto folder1 = std::make_shared<Folder>("A");
auto folder2 = std::make_shared<Folder>("B");
folder1->add(folder2);
folder2->add(folder1);  // 순환!

해결: 부모 포인터를 추가하여 순환을 감지하거나, weak_ptr을 사용하세요.

// ✅ 좋은 예: 부모 체크
class Folder : public FileSystemItem {
    std::weak_ptr<Folder> parent_;
public:
    void add(std::shared_ptr<FileSystemItem> item) {
        // 순환 체크 로직
        children_.push_back(std::move(item));
    }
};

문제 3: 메모리 누수

// ❌ 나쁜 예: raw pointer 사용
class Composite {
    std::vector<Component*> children_;  // 누수 위험
};

해결: std::shared_ptr 또는 std::unique_ptr을 사용하세요.

// ✅ 좋은 예
class Composite {
    std::vector<std::shared_ptr<Component>> children_;
};

5. 프로덕션 패턴

패턴 1: Visitor와 조합

class Visitor {
public:
    virtual void visitFile(File* file) = 0;
    virtual void visitFolder(Folder* folder) = 0;
};
class SizeCalculator : public Visitor {
    int total_ = 0;
public:
    void visitFile(File* file) override { total_ += file->getSize(); }
    void visitFolder(Folder* folder) override {
        for (auto& child : folder->getChildren())
            child->accept(this);
    }
    int getTotal() const { return total_; }
};

패턴 2: Iterator와 조합

class Composite {
    std::vector<std::shared_ptr<Component>> children_;
public:
    auto begin() { return children_.begin(); }
    auto end() { return children_.end(); }
};
// 사용
for (auto& child : composite) {
    child->operation();
}

6. 완전한 예제: 조직도 시스템

#include <vector>
#include <memory>
#include <iostream>
#include <string>
class Employee {
public:
    virtual void showDetails(int indent = 0) const = 0;
    virtual int getSalary() const = 0;
    virtual void add(std::shared_ptr<Employee>) {}
    virtual ~Employee() = default;
};
class Developer : public Employee {
    std::string name_;
    int salary_;
public:
    Developer(std::string name, int salary) 
        : name_(std::move(name)), salary_(salary) {}
    
    void showDetails(int indent = 0) const override {
        std::cout << std::string(indent, ' ') << "Developer: " << name_ 
                  << " ($" << salary_ << ")\n";
    }
    
    int getSalary() const override { return salary_; }
};
class Manager : public Employee {
    std::string name_;
    int salary_;
    std::vector<std::shared_ptr<Employee>> team_;
public:
    Manager(std::string name, int salary) 
        : name_(std::move(name)), salary_(salary) {}
    
    void add(std::shared_ptr<Employee> emp) override {
        team_.push_back(std::move(emp));
    }
    
    void showDetails(int indent = 0) const override {
        std::cout << std::string(indent, ' ') << "Manager: " << name_ 
                  << " ($" << salary_ << ") - Team size: " << team_.size() << '\n';
        for (const auto& emp : team_)
            emp->showDetails(indent + 2);
    }
    
    int getSalary() const override {
        int total = salary_;
        for (const auto& emp : team_)
            total += emp->getSalary();
        return total;
    }
};
int main() {
    auto ceo = std::make_shared<Manager>("Alice", 150000);
    
    auto engManager = std::make_shared<Manager>("Bob", 120000);
    engManager->add(std::make_shared<Developer>("Charlie", 80000));
    engManager->add(std::make_shared<Developer>("David", 85000));
    ceo->add(engManager);
    
    auto salesManager = std::make_shared<Manager>("Eve", 110000);
    salesManager->add(std::make_shared<Developer>("Frank", 70000));
    ceo->add(salesManager);
    
    ceo->showDetails();
    std::cout << "\nTotal company payroll: $" << ceo->getSalary() << '\n';
    
    // 출력:
    // Manager: Alice ($150000) - Team size: 2
    //   Manager: Bob ($120000) - Team size: 2
    //     Developer: Charlie ($80000)
    //     Developer: David ($85000)
    //   Manager: Eve ($110000) - Team size: 1
    //     Developer: Frank ($70000)
    //
    // Total company payroll: $615000
    
    return 0;
}

정리

항목설명
목적leaf와 composite를 동일 인터페이스로 재귀 처리
장점트리 구조를 일관된 API로 다룸, 새 종류의 node 추가 용이, 클라이언트 코드 단순화
단점leaf에 의미 없는 add 등 메서드 노출, 타입 안전성 약화 가능
사용 시기파일 시스템, UI 계층, 조직도, 메뉴 구조 등 트리 형태 데이터
관련 글: Adapter 패턴, Decorator 패턴, 반복자 가이드, Visitor 패턴, Flyweight 패턴.
한 줄 요약: Composite 패턴으로 폴더/파일·메뉴 계층·조직도처럼 트리 구조를 같은 인터페이스로 재귀적으로 다룰 수 있습니다.

같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.


이 글에서 다루는 키워드 (관련 검색어)

C++, Composite, design pattern, structural, tree, hierarchy, recursive 등으로 검색하시면 이 글이 도움이 됩니다.

자주 묻는 질문 (FAQ)

Q. 이 내용을 실무에서 언제 쓰나요?

A. C++ Composite 패턴 완벽 가이드. leaf와 composite를 같은 인터페이스로 처리해 트리·폴더·UI 계층을 일관되게 다루는 구조 패턴, 실전 예제, 파일 시스템, UI 컴포넌트까지. 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.

Q. 선행으로 읽으면 좋은 글은?

A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. C++ 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.

Q. 더 깊이 공부하려면?

A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.

관련 글

심화 부록: 구현·운영 관점

이 부록은 앞선 본문에서 다룬 주제(「C++ Composite 패턴 완벽 가이드 | 트리 구조를 동일 인터페이스로 다루기」)를 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(I/O·네트워크·동시성) → 관측의 흐름으로 장애를 나누면 원인 추적이 빨라집니다.

내부 동작과 핵심 메커니즘

flowchart TD
  A[입력·요청·이벤트] --> B[파싱·검증·디코딩]
  B --> C[핵심 연산·상태 전이]
  C --> D[부작용: I/O·네트워크·동시성]
  D --> E[결과·관측·저장]
sequenceDiagram
  participant C as 클라이언트/호출자
  participant B as 경계(런타임·게이트웨이·프로세스)
  participant D as 의존성(API·DB·큐·파일)
  C->>B: 요청/이벤트
  B->>D: 조회·쓰기·RPC
  D-->>B: 지연·부분 실패·재시도 가능
  B-->>C: 응답 또는 오류(코드·상관 ID)
  • 불변 조건(Invariant): 버퍼 경계, 프로토콜 상태, 트랜잭션 격리, FD 상한 등 단계별로 문장으로 적어 두면 디버깅 비용이 줄어듭니다.
  • 결정성: 순수 층과 시간·네트워크·스케줄에 의존하는 층을 분리해야 테스트와 장애 분석이 쉬워집니다.
  • 경계 비용: 직렬화, 인코딩, syscall 횟수, 락 경합, 할당·GC, 캐시 미스를 의심 목록에 둡니다.
  • 백프레셔: 생산자가 소비자보다 빠를 때 버퍼·큐·스트림에서 속도를 줄이는 신호를 어디에 둘지 정의합니다.

프로덕션 운영 패턴

영역운영 관점 질문
관측성요청 단위 상관 ID, 에러율·지연 p95/p99, 의존성 타임아웃·재시도가 대시보드에 보이는가
안전성입력 검증·권한·비밀·감사 로그가 코드 경로마다 일관적인가
신뢰성재시도는 멱등 연산에만 적용되는가, 서킷 브레이커·백오프·DLQ가 있는가
성능캐시·배치 크기·커넥션 풀·인덱스·백프레셔가 데이터 규모에 맞는가
배포롤백 룬북, 카나리/블루그린, 마이그레이션·피처 플래그가 문서화되어 있는가
용량피크 트래픽·디스크·FD·스레드 풀 상한을 주기적으로 검증하는가

스테이징은 데이터 양·네트워크 RTT·동시성을 프로덕션에 가깝게 맞출수록 재현율이 올라갑니다.

확장 예시: 엔드투엔드 미니 시나리오

앞선 본문 주제(「C++ Composite 패턴 완벽 가이드 | 트리 구조를 동일 인터페이스로 다루기」)를 배포·운영 흐름에 맞춰 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.

  1. 입력 계약 고정: 스키마·버전·최대 페이로드·타임아웃·에러 코드를 경계에 둔다.
  2. 핵심 경로 계측: 요청 ID, 단계별 지연, 외부 호출 결과 코드를 로그·메트릭·트레이스에서 한 흐름으로 본다.
  3. 실패 주입: 의존성 타임아웃·5xx·부분 데이터·락 대기를 스테이징에서 재현한다.
  4. 호환·롤백: 설정/마이그레이션/클라이언트 버전을 되돌릴 수 있는지 확인한다.
  5. 부하 후 검증: 피크 대비 p95/p99, 에러율, 리소스 상한, 알림 임계값을 점검한다.
handle(request):
  ctx = newCorrelationId()
  validated = validateSchema(request)
  authorize(validated, ctx)
  result = domainCore(validated)
  persistOrEmit(result, idempotentKey)
  recordMetrics(ctx, latency, outcome)
  return result

문제 해결(Troubleshooting)

증상가능 원인조치
간헐적 실패레이스, 타임아웃, 외부 의존성, DNS최소 재현 스크립트, 분산 트레이스·로그 상관관계, 재시도·서킷 설정 점검
성능 저하N+1, 동기 I/O, 락 경합, 과도한 직렬화, 캐시 미스프로파일러·APM으로 핫스팟 확인 후 한 가지씩 제거
메모리 증가캐시 무제한, 구독/리스너 누수, 대용량 버퍼, 커넥션 미반납상한·TTL·힙/FD 스냅샷 비교
빌드·배포만 실패환경 변수, 권한, 플랫폼 차이, lockfileCI 로그와 로컬 diff, 런타임·이미지 버전 핀
설정 불일치프로필·시크릿·기본값, 리전스키마 검증된 설정 단일 소스와 배포 매트릭스 표준화
데이터 불일치비멱등 재시도, 부분 쓰기, 캐시 무효화 누락멱등 키·아웃박스·트랜잭션 경계 재검토

권장 순서: (1) 최소 재현 (2) 최근 변경 범위 축소 (3) 환경·의존성 차이 (4) 관측으로 가설 검증 (5) 수정 후 회귀·부하 테스트.

배포 전에는 git addgit commitgit pushnpm run deploy 순서를 권장합니다.