복합체 패턴(Composite Pattern)은 구조적 디자인 패턴으로, 객체를 트리 구조로 구성하여 개별 객체와 객체 그룹을 동일하게 취급할 수 있도록 한다.
이를 통해 클라이언트는 단일 객체와 복합 객체를 구별하지 않고 다룰 수 있다.
소프트웨어 개발에서 개별 요소와 복합 요소를 처리하는 로직이 각각 다르다면 코드 중복과 복잡성이 증가한다.
복합체 패턴을 사용하면 다음과 같은 이점을 얻을 수 있다:
파일 시스템에서 파일과 폴더는 모두 열기
, 복사
, 삭제
같은 공통 동작을 가진다.
복합체 패턴을 사용하면 파일과 폴더를 동일한 인터페이스로 처리할 수 있다.
Component
↑
Composite ←──── Leaf
이번 예시에서는 “파일과 폴더의 트리 구조”를 복합체 패턴으로 구현해보겠다.
// Component 인터페이스
interface FileSystemComponent {
void display();
}
// Leaf 클래스
class File implements FileSystemComponent {
private String name;
public File(String name) {
this.name = name;
}
@Override
public void display() {
System.out.println("파일: " + name);
}
}
// Composite 클래스
class Folder implements FileSystemComponent {
private String name;
private List<FileSystemComponent> components = new ArrayList<>();
public Folder(String name) {
this.name = name;
}
public void add(FileSystemComponent component) {
components.add(component);
}
public void remove(FileSystemComponent component) {
components.remove(component);
}
@Override
public void display() {
System.out.println("폴더: " + name);
for (FileSystemComponent component : components) {
component.display();
}
}
}
// 클라이언트 코드
public class Main {
public static void main(String[] args) {
FileSystemComponent file1 = new File("문서1.txt");
FileSystemComponent file2 = new File("문서2.txt");
FileSystemComponent file3 = new File("이미지.png");
Folder folder1 = new Folder("문서 폴더");
folder1.add(file1);
folder1.add(file2);
Folder rootFolder = new Folder("루트 폴더");
rootFolder.add(folder1);
rootFolder.add(file3);
// 전체 파일 시스템 출력
rootFolder.display();
}
}
폴더: 루트 폴더
폴더: 문서 폴더
파일: 문서1.txt
파일: 문서2.txt
파일: 이미지.png
복합체 패턴(Composite Pattern)은 개별 객체와 복합 객체를 동일하게 처리할 수 있는 강력한 구조적 패턴이다.
특히, 계층적 데이터를 다룰 때 유용하며, 클라이언트 코드를 단순화할 수 있다.
아래 글에서 다른 디자인 패턴들을 확인할 수 있다.
디자인 패턴 모음