카테고리 없음

11. Composite - 그릇과 내용물을 동일시한다

조요피 2023. 10. 16. 17:55

11. Composite - 그릇과 내용물을 동일시한다

Composite 패턴은 객체 지향 소프트웨어 디자인에서 사용되는 구조적 디자인 패턴 중 하나로, 계층 구조로 이루어진 객체를 다루는 데 유용합니다. 이 패턴은 개별 객체와 객체의 컨테이너(그룹)를 동일한
인터페이스를 통해 다룰 수 있도록 합니다. 주로 트리 구조와 같은 계층 구조에서 사용됩니다.

Composite 패턴은 다음의 주요 구성 요소로 이루어집니다:

  1. Component: Component는 인터페이스 또는 추상 클래스로 정의됩니다. 이는 개별 객체와 컨테이너 객체에 대한 공통 메서드를 정의합니다. 예를 들어, 그룹과 개별 항목을 나타내는 객체는 모두
    Component 인터페이스를 구현하거나 상속받습니다.

  2. Leaf: Leaf 클래스는 개별 객체를 나타내며 Component를 구현합니다. 이러한 개별 객체는 더 이상 하위 항목을 포함하지 않습니다.

  3. Composite: Composite 클래스는 컨테이너 객체를 나타내며 Component를 구현합니다. 이러한 컨테이너 객체는 자식 Component를 가질 수 있으며 이 자식 Component들을 관리하는
    메서드를 구현합니다. 이로써 Composite 객체는 개별 객체와 다른 Composite 객체를 포함할 수 있습니다.

Composite 패턴의 주요 장점은 다음과 같습니다:

  • 개별 객체와 컨테이너 객체를 동일한 방식으로 다룰 수 있으므로 클라이언트 코드가 단순해집니다.
  • 계층 구조를 쉽게 확장하고 수정할 수 있으며, 복합 객체를 사용하여 복잡한 구조를 나타낼 수 있습니다.
  • 클라이언트 코드는 계층 구조의 세부 사항을 모른 채, 일반적인 Component 인터페이스를 사용하여 작업을 수행할 수 있습니다.

예를 들어, 그래픽 사용자 인터페이스 구성 요소에서 Composite 패턴을 사용할 수 있으며, 버튼, 패널, 창 등의 개별 구성 요소와 이러한 구성 요소로 이루어진 복합 구성 요소를 만들 수 있습니다. 클라이언트
코드는 모든 구성 요소를 동일한 방식으로 다룰 수 있습니다.

간단한 Java 예제로 Composite 패턴을 보여줄 수 있으나, 자세한 구현은 프로젝트의 요구사항에 따라 다를 수 있습니다.

예제

Composite 패턴의 간단한 Java 예제 코드를 제공하겠습니다. 이 예제에서는 파일 시스템을 모델링하고, 파일과 디렉터리를 나타내는 Component 인터페이스를 정의하고, 이를 구체적으로 구현하는 Leaf(
파일)와 Composite(디렉터리) 클래스를 만들 것입니다.

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

// Component 인터페이스
interface Component {
    void showName();
}

// Leaf 클래스 (파일)
class File implements Component {
    private String name;

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

    @Override
    public void showName() {
        System.out.println("File: " + name);
    }
}

// Composite 클래스 (디렉터리)
class Directory implements Component {
    private String name;
    private List<Component> components = new ArrayList<>();

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

    public void addComponent(Component component) {
        components.add(component);
    }

    @Override
    public void showName() {
        System.out.println("Directory: " + name);
        for (Component component : components) {
            component.showName();
        }
    }
}

public class CompositePatternExample {
    public static void main(String[] args) {
        // 디렉터리와 파일 생성
        Directory rootDir = new Directory("Root");
        File file1 = new File("file1.txt");
        File file2 = new File("file2.txt");
        Directory subDir = new Directory("Subdirectory");
        File file3 = new File("file3.txt");

        // 디렉터리에 파일 및 다른 디렉터리 추가
        rootDir.addComponent(file1);
        rootDir.addComponent(file2);
        rootDir.addComponent(subDir);
        subDir.addComponent(file3);

        // 디렉터리 구조 출력
        rootDir.showName();
    }
}

이 예제에서는 Component 인터페이스를 정의하고, Leaf(파일) 및 Composite(디렉터리) 클래스를 구현합니다. 그리고 디렉터리에 파일 및 다른 디렉터리를 추가하여 계층 구조를 만들고, 디렉터리 구조를
출력하는 간단한 예제입니다. Composite 패턴을 사용하면 디렉터리와 파일을 동일한 방식으로 다룰 수 있습니다.