Posted:      Updated:

자바 디자인 패턴 스터디를 하며 ‘Java 객체 지향 디자인 패턴’ 교재를 정리한 글입니다.

컴퍼지트 패턴(Composite Pattern)

  • 부분, 전체의 관계를 갖는 객체들을 정의할 때 유용함
  • 클라이언트에서 전체와 부분을 구분하지 않고 동일한 인터페이스 사용 가능

컴퍼지트 패턴 컬레보레이션

  • Component
    • Leaf 클래스와 Composite 클래스의 공동 인터페이스 정의
  • Leaf
    • 구체적인 부분 클래스
    • Composite 객체의 부품으로 설정
  • Composite
    • 전체 클래스
    • 복수 개의 Component 를 가짐
    • 복수 개의 Leaf, Component 객체를 부분으로 가질 수 있음

예시: 택배 비용 계산하기

전체 코드

public abstract class ParcelItem {
    protected int weight;

    public ParcelItem(int weight) {
        this.weight = weight;
    }

    public abstract int price();
}

public class Box extends ParcelItem{
    private List<ParcelItem> items = new ArrayList<>();

    public Box(int weight) {
        super(weight);
    }

    @Override
    public int price() {
        int totalPrice = 0;

        for (ParcelItem item : items) {
            totalPrice += item.price();
        }

        return totalPrice;
    }

    public void addItems(ParcelItem item) {
        items.add(item);
    }
}

public class Socks extends ParcelItem{
    public Socks(int weight) {
        super(weight);
    }

    @Override
    public int price() {
        return weight/100*200;
    }
}

댓글남기기