HW4의 Level 3와 관련된 개념인 Composite Pattern 이라는 것에 대해서 알아봅시다
OOP에서 트리 구조를 작성하기 위한 기법
파일 폴더 .... 한번 Java로 작성해 봅시다
실제 파일 시스템을 읽어들이는 프로그램을 만드는 게 아니라 그냥 개념만 따라서
abstract class Node { // 추상 클래스
String name; // 파일 또는 폴더의 이름
Node(String name) { this.name = name; }
abstract void display();
}
class Dir extends Node { // 디렉토리 노드
Node nodes[];
Dir(String name, Node nodes[]) { super(name); this.nodes = nodes; }
@Override
void display() {
System.out.print(name); // 디렉토리 이름으로 시작
System.out.print("{ ");
for (Node n : nodes) {
n.display(); // 포함하는 각각의 노드를 display
System.out.print("; ");
}
System.out.print("}");
}
}
class File extends Node { // 파일 노드
File(String name) { super(name); }
@Override
void display() { System.out.print(name); } // 파일 이름 출력
}
File file1 = new File("hello.txt");
File file2 = new File("main.java");
File file3 = new File("index.html");
file1.display();
hello.txt
Node ns1[] = { file1, file2 };
Dir dir1 = new Dir("Work", ns1);
dir1.display();
Work{ hello.txt; main.java; }
Node ns2[] = { file3, dir1 };
Dir dir2 = new Dir("Root", ns2);
dir2.display();
Root{ index.html; Work{ hello.txt; main.java; }; }