1 개요[ | ]
- "그릇과 내용물을 동일시하기"
- 객체들의 관계를 트리 구조로 구성하여 부분-전체 계층을 표현하는 패턴
- 단일 객체와 복합 객체를 동일하게 다룰 수 있다.
- 각 객체를 독립적으로 처리하거나 중첩된(nested) 객체들의 집합을 동일한 인터페이스를 통해 처리할 수 있는 객체 계층구조를 생성할 수 있다.
- 적용사례: GUI 컴포넌트
2 구조[ | ]
- 왼쪽 패턴(획일형)은 자식 관리 메소드(add/remove/getChild)가 Component에 구현된 형태이다. 모든 컴포넌트를 동일하게 다룰 수 있다는 장점이 있지만, 런타임 중에 Client가 자식이 없는 Leaf 컴포넌트에 대해 의미 없이 자식 관리 메소드를 잘못 호출할 수 있다는 단점이 있다.
- 오른쪽 패턴(안전형)은 자식 관리 메소드(add/remove/getChild)가 컴포지트에 구현된 형태이다. Leaf 컴포넌트의 자식 관리 메소드에 대한 접근을 사전에 차단할 수 있어 안전하다. Leaf와 Composite 컴포넌트가 다른 인터페이스를 가지게 된다는 단점은 있다.
3 예제[ | ]
Java
Copy
import java.util.List;
import java.util.ArrayList;
/** "Component" */
interface Graphic {
//Prints the graphic.
public void print();
}
/** "Composite" */
class CompositeGraphic implements Graphic {
//Collection of child graphics.
private List<Graphic> mChildGraphics = new ArrayList<Graphic>();
//Prints the graphic.
public void print() {
for (Graphic graphic : mChildGraphics) {
graphic.print();
}
}
//Adds the graphic to the composition.
public void add(Graphic graphic) {
mChildGraphics.add(graphic);
}
//Removes the graphic from the composition.
public void remove(Graphic graphic) {
mChildGraphics.remove(graphic);
}
}
/** "Leaf" */
class Ellipse implements Graphic {
//Prints the graphic.
public void print() {
System.out.println("Ellipse");
}
}
/** Client */
public class Program {
public static void main(String[] args) {
//Initialize four ellipses
Ellipse ellipse1 = new Ellipse();
Ellipse ellipse2 = new Ellipse();
Ellipse ellipse3 = new Ellipse();
Ellipse ellipse4 = new Ellipse();
//Initialize three composite graphics
CompositeGraphic graphic = new CompositeGraphic();
CompositeGraphic graphic1 = new CompositeGraphic();
CompositeGraphic graphic2 = new CompositeGraphic();
//Composes the graphics
graphic1.add(ellipse1);
graphic1.add(ellipse2);
graphic1.add(ellipse3);
graphic2.add(ellipse4);
graphic.add(graphic1);
graphic.add(graphic2);
//Prints the complete graphic (four times the string "Ellipse").
graphic.print();
}
}
4 같이 보기[ | ]
5 참고[ | ]
편집자 Jmnote
로그인하시면 댓글을 쓸 수 있습니다.