본 콘텐츠의 이미지 및 내용은 AI로 생성되었습니다.
본 콘텐츠의 이미지 및 내용을 무단으로 복제, 배포, 수정하여 사용할 경우 저작권법에 의해 법적 제재를 받을 수 있습니다.
이미지 로딩 중...
AI Generated
2025. 11. 5. · 171 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)
함께 보면 좋은 카드 뉴스
마이크로서비스 배포 완벽 가이드
Kubernetes를 활용한 마이크로서비스 배포의 핵심 개념부터 실전 운영까지, 초급 개발자도 쉽게 따라할 수 있는 완벽 가이드입니다. 실무에서 바로 적용 가능한 배포 전략과 노하우를 담았습니다.
Application Load Balancer 완벽 가이드
AWS의 Application Load Balancer를 처음 배우는 개발자를 위한 실전 가이드입니다. ALB 생성부터 ECS 연동, 헬스 체크, HTTPS 설정까지 실무에 필요한 모든 내용을 다룹니다. 초급 개발자도 쉽게 따라할 수 있도록 단계별로 설명합니다.
고객 상담 AI 시스템 완벽 구축 가이드
AWS Bedrock Agent와 Knowledge Base를 활용하여 실시간 고객 상담 AI 시스템을 구축하는 방법을 단계별로 학습합니다. RAG 기반 지식 검색부터 Guardrails 안전 장치, 프론트엔드 연동까지 실무에 바로 적용 가능한 완전한 시스템을 만들어봅니다.
에러 처리와 폴백 완벽 가이드
AWS API 호출 시 발생하는 에러를 처리하고 폴백 전략을 구현하는 방법을 다룹니다. ThrottlingException부터 서킷 브레이커 패턴까지, 실전에서 바로 활용할 수 있는 안정적인 에러 처리 기법을 배웁니다.
AWS Bedrock 인용과 출처 표시 완벽 가이드
AWS Bedrock의 Citation 기능을 활용하여 AI 응답의 신뢰도를 높이는 방법을 배웁니다. 출처 추출부터 UI 표시, 검증까지 실무에서 바로 사용할 수 있는 완전한 가이드입니다.