관리 메뉴

나만의공간

🧱 1. 복합체 패턴이란? 본문

IT/JAVA

🧱 1. 복합체 패턴이란?

밥알이 2025. 5. 31. 23:58

복합체 패턴(Composite Pattern)이란? 트리 구조를 우아하게 처리하는 디자인 패턴

복합체 패턴(Composite Pattern)은 객체들을 트리 구조로 구성하여, 개별 객체와 복합 객체를 동일한 방식으로 처리할 수 있도록 도와주는 구조 패턴입니다. 즉, 부분과 전체를 같은 인터페이스로 다룰 수 있게 해주는 것이 핵심입니다.

📌 복합체 패턴의 핵심 정의

  • 객체들을 계층 구조로 구성 (트리 구조)
  • Leaf(개별 객체)와 Composite(복합 객체)를 동일하게 다룸
  • 클라이언트가 객체 구조의 복잡성을 신경 쓰지 않아도 됨

🎨 실생활 비유: 파일 탐색기

Windows 탐색기나 Mac의 Finder를 생각해보세요. 폴더 안에는 파일이 있고, 또 다른 폴더가 들어갈 수 있죠.

📁 root
 ├─ 📄 README.md
 └─ 📁 sub
     └─ 📁 logs
         ├─ 📄 app.log
         └─ 📄 errors.log

우리는 파일이든 폴더든 똑같이 탐색하거나 출력할 수 있어야 합니다. 이것이 바로 복합체 패턴의 아이디어입니다.

언제 복합체 패턴을 사용해야 할까?

✅ 사용 시점

  • 트리 구조 데이터(폴더 구조, 메뉴 구조 등)를 다룰 때
  • 클라이언트 코드가 부분과 전체를 구분하지 않고 처리하길 원할 때
  • 복잡한 계층 구조를 재사용성과 유연성을 고려해 설계하고 싶을 때

 

🎯 복합체 패턴 실무 예제 (Java)

구현 개요

  • FileComponent: 공통 인터페이스
  • File: 실제 파일 (Leaf)
  • Directory: 폴더 (Composite)

📁 1. 공통 인터페이스

public interface FileComponent {
    void print(String indent);
}

📁 2. Leaf 클래스: 파일

public class File implements FileComponent {
    private String name;

    public File(String name) {
        this.name = name;
    }

    @Override
    public void print(String indent) {
        System.out.println(indent + "- 📄 " + name);
    }
}

📁 3. Composite 클래스: 폴더

import java.util.ArrayList;
import java.util.List;

public class Directory implements FileComponent {
    private String name;
    private List children = new ArrayList<>();

    public Directory(String name) {
        this.name = name;
    }

    public void add(FileComponent component) {
        children.add(component);
    }

    public void remove(FileComponent component) {
        children.remove(component);
    }

    @Override
    public void print(String indent) {
        System.out.println(indent + "+ 📁 " + name);
        for (FileComponent child : children) {
            child.print(indent + "   ");
        }
    }
}

📁 4. 사용 예시

public class Main {
    public static void main(String[] args) {
        Directory root = new Directory("root");
        Directory subFolder = new Directory("sub");
        Directory logs = new Directory("logs");

        File file1 = new File("README.md");
        File file2 = new File("app.log");
        File file3 = new File("errors.log");

        root.add(file1);
        root.add(subFolder);

        subFolder.add(logs);
        logs.add(file2);
        logs.add(file3);

        root.print("");
    }
}

✅ 실행 결과

+ 📁 root
   - 📄 README.md
   + 📁 sub
      + 📁 logs
         - 📄 app.log
         - 📄 errors.log

📦 구조 요약 (UML)

        FileComponent (interface)
             ▲
       ┌─────┴─────┐
     File       Directory
                 ▲
        (children: List)

💡 실무 활용 예시

실무 사례 설명
메뉴 UI 메뉴 그룹과 항목을 동일한 방식으로 구성
조직도 부서, 팀, 직원 등 계층적 구조를 단일 인터페이스로 처리
파일 시스템 폴더/파일 계층 구조 표현
HTML 트리 DOM 요소를 계층적으로 구성

👍 복합체 패턴의 장점과 단점

✅ 장점

  • 확장성: 새로운 노드 타입을 손쉽게 추가 가능
  • 일관성: Leaf와 Composite를 동일하게 처리
  • 유지보수성: 구조적 일관성으로 인한 코드 재사용성 향상

⚠️ 단점

  • 단순한 경우에는 오히려 설계가 복잡해질 수 있음
  • Leaf/Composite 타입 구분이 명확하지 않으면 혼란스러울 수 있음

📝 요약 정리

항목 설명
패턴 이름 복합체 패턴 (Composite Pattern)
핵심 목적 부분-전체 구조를 동일한 인터페이스로 다루기
주요 구성 요소 Component, Leaf, Composite
대표 적용 사례 파일 시스템, 조직도, 메뉴 구조, HTML DOM

🔚 마무리: 복합체 패턴은 복잡한 트리 구조를 단순하게

복합체 패턴은 계층 구조를 다룰 때 매우 강력한 설계 도구입니다. 개별 객체와 복합 객체를 구분하지 않고 일관된 방식으로 처리할 수 있다는 점에서, UI 메뉴, 폴더 구조, 조직도 등 다양한 분야에서 널리 사용됩니다. 구조가 익숙해지면 실무에서 매우 자주 활용되는 패턴이니 꼭 익혀두세요!

Comments