그룹 전체와 객체를 동일하게 처리할 수 있는 패턴. 클라이언트 입장에서는 ‘전체’나 ‘부분’이나 모두 동일한 컴포넌트로 인식할 수는 있는 계층 구조(트리 구조)를 만든다.

Untitled

Component

모든 component 들을 위한 추상화된 개념으로써, "Leaf" 와 "Composite" 클래스의 인터페이스이다.

Leaf

"Component" 인터페이스를 구현한, 구체 클래스를 나타낸다.

Composite

"Component"  인터페이스를 구현하고, 구현되는 자식(Leaf or Composite) 들을 가지고 관리하기 위한 메소드(addChild, removeChild...)를 구현한다.

일반적으로 인터페이스에 작성된 메소드는 자식에게 위임하는 처리를 한다.

Untitled

"Client" 에서 트리 구조에서의 top-level 에 존재하는 "Composite1" 에 요청을 보낸다.

그러면 "Component" 인터페이스를 구현한 객체들은 트리 구조를 토대로 위에서 아래 방향으로 모든 자식 요소에게 전달하게 된다.

예제


public class Item {

    private String name;

    private int price;

    public Item(String name, int price) {
        this.name = name;
        this.price = price;
    }

    public int getPrice() {
        return this.price;
    }
}