본 콘텐츠의 이미지 및 내용은 AI로 생성되었습니다.
본 콘텐츠의 이미지 및 내용을 무단으로 복제, 배포, 수정하여 사용할 경우 저작권법에 의해 법적 제재를 받을 수 있습니다.
이미지 로딩 중...
AI Generated
2025. 11. 5. · 205 Views
Composite Pattern 핵심 개념 완벽 정리
객체들을 트리 구조로 구성하여 부분-전체 계층을 표현하는 Composite Pattern의 핵심 개념을 실제 예제와 함께 학습합니다. 파일 시스템, UI 컴포넌트 등 실무에서 자주 사용되는 패턴입니다.
들어가며
이 글에서는 Composite Pattern 핵심 개념 완벽 정리에 대해 상세히 알아보겠습니다. 총 10가지 주요 개념을 다루며, 각각의 개념에 대한 설명과 실제 코드 예제를 함께 제공합니다.
목차
- Component_인터페이스_정의
- Leaf_클래스_구현
- Composite_클래스_구현
- 파일_시스템_예제_File
- 파일_시스템_예제_Directory
- UI_컴포넌트_트리_구조
- 실전_사용_예제
- 재귀적_크기_계산
- 방문자_패턴_결합
- 안전한_Composite_구현
1. Component 인터페이스 정의
개요
Composite Pattern의 기본이 되는 공통 인터페이스를 정의합니다. 개별 객체와 복합 객체 모두 동일한 인터페이스를 구현합니다.
코드 예제
interface Component {
operation(): string;
add?(child: Component): void;
remove?(child: Component): void;
getChild?(index: number): Component;
}
설명
Component 인터페이스는 Leaf와 Composite 클래스가 공통으로 구현할 메서드를 정의합니다. 옵셔널 메서드는 Composite에서만 구현됩니다.
2. Leaf 클래스 구현
개요
트리 구조의 말단 노드를 나타내는 Leaf 클래스입니다. 자식을 가질 수 없는 개별 객체를 표현합니다.
코드 예제
class Leaf implements Component {
constructor(private name: string) {}
operation(): string {
return `Leaf: ${this.name}`;
}
}
설명
Leaf는 가장 기본적인 단위 객체로, 자식을 추가하거나 제거할 수 없습니다. operation 메서드만 구현합니다.
3. Composite 클래스 구현
개요
자식 컴포넌트들을 포함할 수 있는 복합 객체입니다. 자식들을 관리하고 operation을 위임합니다.
코드 예제
class Composite implements Component {
private children: Component[] = [];
constructor(private name: string) {}
add(child: Component): void {
this.children.push(child);
}
operation(): string {
const results = this.children.map(c => c.operation());
return `Composite: ${this.name}(${results.join(', ')})`;
}
}
설명
Composite는 Component 배열로 자식들을 관리하며, operation 호출 시 모든 자식의 operation을 실행합니다.
4. 파일 시스템 예제 File
개요
실제 파일 시스템을 모델링한 예제입니다. File은 Leaf에 해당하는 개별 파일을 나타냅니다.
코드 예제
class File implements Component {
constructor(private name: string, private size: number) {}
operation(): string {
return `File: ${this.name} (${this.size}KB)`;
}
getSize(): number {
return this.size;
}
}
설명
File 클래스는 파일명과 크기를 가지며, 자식을 가질 수 없는 단일 파일을 표현합니다.
5. 파일 시스템 예제 Directory
개요
Directory는 Composite에 해당하며, File이나 다른 Directory를 포함할 수 있습니다.
코드 예제
class Directory implements Component {
private children: Component[] = [];
constructor(private name: string) {}
add(child: Component): void {
this.children.push(child);
}
operation(): string {
const items = this.children.map(c => c.operation()).join('\n ');
return `Directory: ${this.name}\n ${items}`;
}
}
설명
Directory는 여러 File과 하위 Directory를 포함하며, 재귀적으로 전체 구조를 출력할 수 있습니다.
6. UI 컴포넌트 트리 구조
개요
UI 프레임워크에서 자주 사용되는 컴포넌트 트리 구조를 Composite Pattern으로 구현합니다.
코드 예제
abstract class UIComponent {
abstract render(): string;
}
class Button extends UIComponent {
render(): string { return '<button>Click</button>'; }
}
class Panel extends UIComponent {
private children: UIComponent[] = [];
add(child: UIComponent) { this.children.push(child); }
render(): string {
return `<div>${this.children.map(c => c.render()).join('')}</div>`;
}
}
설명
Panel은 여러 UI 컴포넌트를 포함하며, 모든 자식의 render를 호출하여 전체 UI를 생성합니다.
7. 실전 사용 예제
개요
Composite Pattern을 실제로 사용하는 예제입니다. 파일 시스템 구조를 생성하고 탐색합니다.
코드 예제
const root = new Directory('root');
const home = new Directory('home');
home.add(new File('config.json', 10));
home.add(new File('data.txt', 25));
const docs = new Directory('documents');
docs.add(new File('resume.pdf', 150));
root.add(home);
root.add(docs);
console.log(root.operation());
설명
계층적 구조를 쉽게 생성하고, 단일 메서드 호출로 전체 트리를 순회할 수 있습니다.
8. 재귀적 크기 계산
개요
Composite Pattern의 장점인 재귀적 처리를 활용하여 전체 디렉토리 크기를 계산합니다.
코드 예제
interface SizeCalculable {
getSize(): number;
}
class FileNode implements SizeCalculable {
constructor(private size: number) {}
getSize(): number { return this.size; }
}
class DirectoryNode implements SizeCalculable {
private children: SizeCalculable[] = [];
add(child: SizeCalculable) { this.children.push(child); }
getSize(): number {
return this.children.reduce((sum, c) => sum + c.getSize(), 0);
}
}
설명
각 노드의 getSize를 재귀적으로 호출하여 전체 크기를 계산합니다. Leaf는 자신의 크기를, Composite는 모든 자식의 합을 반환합니다.
9. 방문자 패턴 결합
개요
Composite Pattern과 Visitor Pattern을 결합하여 더 유연한 작업 수행이 가능합니다.
코드 예제
interface Visitor {
visitFile(file: File): void;
visitDirectory(dir: Directory): void;
}
class SizeVisitor implements Visitor {
private totalSize = 0;
visitFile(file: File): void {
this.totalSize += file.getSize();
}
visitDirectory(dir: Directory): void {
// Directory 순회 로직
}
getTotal(): number { return this.totalSize; }
}
설명
Visitor Pattern을 사용하면 Component 클래스를 수정하지 않고 새로운 기능을 추가할 수 있습니다.
10. 안전한 Composite 구현
개요
타입 안정성을 보장하는 안전한 Composite 구현 방법입니다. 런타임 에러를 방지합니다.
코드 예제
abstract class SafeComponent {
abstract operation(): string;
}
class SafeLeaf extends SafeComponent {
operation(): string { return 'Leaf'; }
}
class SafeComposite extends SafeComponent {
private children: SafeComponent[] = [];
add(child: SafeComponent): this {
this.children.push(child);
return this;
}
operation(): string {
return this.children.map(c => c.operation()).join(', ');
}
}
설명
추상 클래스를 사용하고 Composite만 add 메서드를 제공하여 타입 안정성을 확보합니다. 메서드 체이닝도 지원합니다.
마치며
이번 글에서는 Composite Pattern 핵심 개념 완벽 정리에 대해 알아보았습니다. 총 10가지 개념을 다루었으며, 각각의 사용법과 예제를 살펴보았습니다.
관련 태그
#TypeScript #CompositePattern #DesignPatterns #TreeStructure #ObjectComposition
이 카드뉴스가 포함된 코스
댓글 (0)
함께 보면 좋은 카드 뉴스
UX와 협업 패턴 완벽 가이드
AI 에이전트와 사용자 간의 효과적인 협업을 위한 UX 패턴을 다룹니다. 프롬프트 핸드오프부터 인터럽트 처리까지, 현대적인 에이전트 시스템 설계의 핵심을 배웁니다.
자가 치유 및 재시도 패턴 완벽 가이드
AI 에이전트와 분산 시스템에서 필수적인 자가 치유 패턴을 다룹니다. 에러 감지부터 서킷 브레이커까지, 시스템을 스스로 복구하는 탄력적인 코드 작성법을 배워봅니다.
Feedback Loops 컴파일러와 CI/CD 완벽 가이드
컴파일러 피드백 루프부터 CI/CD 파이프라인, 테스트 자동화, 자가 치유 빌드까지 현대 개발 워크플로우의 핵심을 다룹니다. 초급 개발자도 쉽게 이해할 수 있도록 실무 예제와 함께 설명합니다.
실전 MCP 통합 프로젝트 완벽 가이드
Model Context Protocol을 활용한 실전 통합 프로젝트를 처음부터 끝까지 구축하는 방법을 다룹니다. 아키텍처 설계부터 멀티 서버 통합, 모니터링, 배포까지 운영 레벨의 MCP 시스템을 구축하는 노하우를 담았습니다.
MCP 동적 도구 업데이트 완벽 가이드
AI 에이전트의 도구를 런타임에 동적으로 로딩하고 관리하는 방법을 알아봅니다. 플러그인 시스템 설계부터 핫 리로딩, 보안까지 실무에서 바로 적용할 수 있는 내용을 다룹니다.