์ปดํฌ์งํธ ํจํด (Composite Pattern)
์ปดํฌ์งํธ ํจํด์ ๊ฐ๋ณ ๊ฐ์ฒด์ ๋ณตํฉ ๊ฐ์ฒด๋ฅผ ๋์ผํ ๋ฐฉ์์ผ๋ก ๋ค๋ฃฐ ์ ์๊ฒ ํด์ฃผ๋ ๊ตฌ์กฐ์ ๋์์ธ ํจํด์
๋๋ค. ํธ๋ฆฌ ๊ตฌ์กฐ๋ก ๊ตฌ์ฑ๋ ๋ถ๋ถ-์ ์ฒด ๊ณ์ธต๊ตฌ์กฐ๋ฅผ ํํํ๋ฉฐ, ํด๋ผ์ด์ธํธ๊ฐ ๊ฐ๋ณ ๊ฐ์ฒด์ ๋ณตํฉ ๊ฐ์ฒด๋ฅผ ๊ท ์ผํ๊ฒ ์ฒ๋ฆฌํ ์ ์๋๋ก ํฉ๋๋ค.
์ฃผ์ ๋ชฉ์
โข
๊ฐ์ฒด๋ค์ ํธ๋ฆฌ ๊ตฌ์กฐ๋ก ๊ตฌ์ฑํ์ฌ ๋ถ๋ถ-์ ์ฒด ๊ณ์ธต์ ํํ
โข
๋จ์ผ ๊ฐ์ฒด์ ๋ณตํฉ ๊ฐ์ฒด๋ฅผ ๋์ผํ ์ธํฐํ์ด์ค๋ก ์ฒ๋ฆฌ
โข
ํด๋ผ์ด์ธํธ ์ฝ๋๋ฅผ ๋จ์ํํ๊ณ ๊ฐ์ฒด ๊ตฌ์กฐ์ ์ผ๊ด์ฑ ์ ์ง
ํน์ง
โข
์ฌ๊ท์ ์ธ ๊ตฌ์กฐ๋ฅผ ๊ฐ๋ฅํ๊ฒ ํจ
โข
Component, Leaf, Composite ํด๋์ค๋ก ๊ตฌ์ฑ
โข
ํ์ฅ์ฑ์ด ์ข๊ณ ๊ฐ์ฒด ์ถ๊ฐ๊ฐ ์ฉ์ดํจ
โข
ํ์
์์ ์ฑ ํ๋ณด๊ฐ ์ด๋ ค์ธ ์ ์์
์์ ์ฝ๋
// Component
interface FileComponent {
void showInfo();
}
// Leaf
class File implements FileComponent {
private String name;
public File(String name) {
this.name = name;
}
public void showInfo() {
System.out.println("File: " + name);
}
}
// Composite
class Directory implements FileComponent {
private String name;
private List<FileComponent> components = new ArrayList<>();
public Directory(String name) {
this.name = name;
}
public void add(FileComponent component) {
components.add(component);
}
public void showInfo() {
System.out.println("Directory: " + name);
for(FileComponent component : components) {
component.showInfo();
}
}
}
Java
๋ณต์ฌ
์ฝ๋ ์ค๋ช
์ ์์ ์ฝ๋๋ ํ์ผ ์์คํ
์ ๊ตฌํํ ์ปดํฌ์งํธ ํจํด์ ์์์
๋๋ค:
โข
FileComponent (Component): ํ์ผ๊ณผ ๋๋ ํ ๋ฆฌ์ ๊ณตํต ์ธํฐํ์ด์ค๋ฅผ ์ ์ํฉ๋๋ค. showInfo() ๋ฉ์๋๋ฅผ ํตํด ์ ๋ณด๋ฅผ ํ์ํฉ๋๋ค.
โข
File (Leaf): ๊ฐ๋ณ ํ์ผ์ ๋ํ๋ด๋ ํด๋์ค๋ก, ๋ง๋จ ๊ฐ์ฒด์
๋๋ค. ํ์ผ๋ช
์ ์ ์ฅํ๊ณ ํ์ํ๋ ๊ธฐ๋ฅ์ ์ํํฉ๋๋ค.
โข
Directory (Composite): ์ฌ๋ฌ FileComponent๋ฅผ ํฌํจํ ์ ์๋ ์ปจํ
์ด๋์
๋๋ค. ํ์ผ๊ณผ ํ์ ๋๋ ํ ๋ฆฌ๋ฅผ ์ ์ฅํ๊ณ ๊ด๋ฆฌํฉ๋๋ค.
์ด ๊ตฌ์กฐ๋ฅผ ํตํด ํด๋ผ์ด์ธํธ๋ ํ์ผ๊ณผ ๋๋ ํ ๋ฆฌ๋ฅผ ๋์ผํ ๋ฐฉ์์ผ๋ก ๋ค๋ฃฐ ์ ์์ผ๋ฉฐ, ๋๋ ํ ๋ฆฌ ๋ด์ ํ์ผ๊ณผ ๋ค๋ฅธ ๋๋ ํ ๋ฆฌ๋ฅผ ์์ ๋กญ๊ฒ ์ถ๊ฐํ ์ ์์ต๋๋ค.
ํ์ฉ ์์
public class Main {
public static void main(String[] args) {
Directory root = new Directory("๋ฃจํธ");
Directory docs = new Directory("๋ฌธ์");
File file1 = new File("report.txt");
File file2 = new File("image.jpg");
docs.add(file1);
root.add(docs);
root.add(file2);
root.showInfo(); // ์ ์ฒด ๊ตฌ์กฐ๋ฅผ ํ์
}
}
Java
๋ณต์ฌ