1. 컴포지트 패턴
객체들을 트리 구조로 구성하여 전체-부분의 관계를 표현하는 패턴
개별 객체와 객체들의 집합을 동일한 방식으로 다룰 수 있게 해주어 복합 객체를 표현하고 조작할 수 있다.
클라이언트가 개별 객체와 복합 객체를 구분하지 않고 동일한 방식으로 다룰 수 있도록 도와준다.
- 사용하는 경우
- 전체-부분 계층 구조를 갖는 객체들을 다룰 때: 객체들이 트리 구조로 구성되어 있고, 개별 객체와 복합 객체를 일관된 방식으로 처리해야 할 때 사용
- 사용자가 개별 객체와 복합 객체를 동일한 방식으로 다루어야 할 때: 클라이언트가 객체들을 구분하지 않고 통일된 인터페이스를 통해 조작해야 할 때 사용
- 구현 방법
컴포지트 패턴의 UML 다이어그램
- Component 인터페이스: 모든 객체에 대한 공통 인터페이스를 정의, 개별 객체와 복합 객체를 동일한 방식으로 다룰 수 있도록 한다.
- Leaf 클래스 : 개별 객체를 표현하는 클래스로, 복합 객체의 구성 요소가 될 수 없다. Component 인터페이스를 구현합니다.
- Composite 클래스 : 복합 객체를 표현하는 클래스로, 다른 객체들을 자식으로 가질 수 있다. Component 인터페이스를 구현하며, 자식 객체들을 관리하는 역할을 수행합니다.
// Component 인터페이스
public interface FileSystemComponent {
void showInfo();
}
// Leaf 클래스: 파일
public class File implements FileSystemComponent {
private String name;
public File(String name) {
this.name = name;
}
@Override
public void showInfo() {
System.out.println("File: " + name);
}
}
// Composite 클래스: 디렉터리
public class Directory implements FileSystemComponent {
private String name;
private List<FileSystemComponent> components;
public Directory(String name) {
this.name = name;
this.components = new ArrayList<>();
}
public void addComponent(FileSystemComponent component) {
components.add(component);
}
public void removeComponent(FileSystemComponent component) {
components.remove(component);
}
@Override
public void showInfo() {
System.out.println("Directory: " + name);
for (FileSystemComponent component : components) {
component.showInfo();
}
}
}
// Client
public class Client {
public static void main(String[] args) {
// 디렉터리와 파일 생성
Directory root = new Directory("Root");
Directory dir1 = new Directory("Folder 1");
Directory dir2 = new Directory("Folder 2");
File file1 = new File("File 1.txt");
File file2 = new File("File 2.txt");
// 디렉터리에 구성 요소 추가
root.addComponent(dir1);
root.addComponent(dir2);
dir1.addComponent(file1);
dir2.addComponent(file2);
// 디렉터리 구조 출력
root.showInfo();
}
}