JAVA

[디자인패턴] Composite 패턴

gom1n 2022. 4. 12. 17:19

컴포지트 패턴(Composite pattern)이란?

객체들의 관계를 트리 구조로 구성하여 부분-전체 계층을 표현하는 패턴

 

 

이런식으로 재귀적 호출이 일어나는 편이다. 

예를 들어 만약 전체 파일 size를 알고 싶다면, Leaf 노드에 있는 getSize함수를 계속해서 호출해 전체 값을 알 수 있다.

이런 식으로 자기 자신이 계속 호출되는 원리이다.

 

이 패턴을 쓸 때 노드의 개념을 사용한다는 것이 인상깊었다.

 

예제 soure file >>

Sample.zip
0.01MB


연습문제

11-1) 파일 시스템 이외에 Composite 패턴이 적용되는 예를 생각해보십시오.

- HTML의 리스트(ul, ol, dl) 과 테이블 등

- Swing

 

11-2) 예제 프로그램에 Entry의 (하위 클래스의) 인스턴스에서 '풀 패스'를 얻는 기능을 추가하려고 합니다.

예를 들어서, File의 인스턴스에서

"/root/usr/Kim/Composite.java"

라는 문자열을 얻으려고 합니다. 이때 예제 프로그램의 어떤 클래스를 어떻게 변경하면 좋을까요?

 

 

public abstract class Entry { 
	protected Entry parent; 
    ...
	File file = new File("Composite.java", 100); youngjin.add(file);
	rootdir.printList();
	public String getFullName() {
		StringBuffer fullname = new StringBuffer(); Entry entry = this;
		do {
			System.out.println("");
			System.out.println("file = " + file.getFullName()); System.out.println("youngjin = " + youngjin.getFullName());
			fullname.insert(0, "/" + entry.getName());
			...
			entry = entry.parent;
		} while (entry != null); 
        return fullname.toString();
    }
}
public class Directory extends Entry {
...
	public Entry add(Entry entry) {
		directory.add(entry);
		entry.parent = this;
		return this;
	}
}

Composite Pattern in Java API