C++ Composite 패턴 완벽 가이드 | 트리 구조를 동일 인터페이스로 다루기
이 글의 핵심
C++ 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++ Adapter Pattern 완벽 가이드 | 인터페이스 변환과 호환성
- C++ Decorator Pattern 완벽 가이드 | 기능 동적 추가와 조합
- C++ 반복자 | “Iterator” 완벽 가이드
- C++ Visitor Pattern | “방문자 패턴” 가이드
이 글에서 다루는 키워드 (관련 검색어)
C++, Composite, design pattern, structural, tree, hierarchy, recursive 등으로 검색하시면 이 글이 도움이 됩니다.
자주 묻는 질문 (FAQ)
Q. 이 내용을 실무에서 언제 쓰나요?
A. C++ Composite 패턴 완벽 가이드. leaf와 composite를 같은 인터페이스로 처리해 트리·폴더·UI 계층을 일관되게 다루는 구조 패턴, 실전 예제, 파일 시스템, UI 컴포넌트까지. 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.
Q. 선행으로 읽으면 좋은 글은?
A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. C++ 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.
Q. 더 깊이 공부하려면?
A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.
관련 글
- C++ Bridge 패턴 완벽 가이드 | 구현과 추상화 분리로 확장성 높이기
- C++ Facade 패턴 완벽 가이드 | 복잡한 서브시스템을 하나의 간단한 인터페이스로
- C++ Flyweight 패턴 완벽 가이드 | 공유로 메모리 절약하기
- C++ 디자인 패턴 | Adapter·Decorator
- 배열과 리스트 | 코딩 테스트 필수 자료구조 완벽 정리