티스토리 뷰

knowledge/pattern

[Pattern] Composite Pattern에 대하여

글을 쓰는 개발자 2021. 11. 29. 22:01
반응형

의도

부분과 전체의 계층을 표현하기 위해 객체들을 모아 트리 구조로 구성. 사용자로 하여금 개별 객체와 복합 객체를 모두 동일하게 다룰 수 있도록 하는 패턴

활용성

부분-전체의 객체 계통을 표현하고 싶을 때

사용자가 객체의 합성으로 생긴 복합 객체와 개개의 객체 사이의 차이를 알지 않고도 자기 일을 할 수 있도록 만들고 싶을 때. 사용자는 복합구조의 모든 객체를 똑같이 취급

참여자

  • Component: 집합 관계에 정의될 모든 객체에 대한 인터페이스를 정의. 모든 클래스에 해당하는 인터페이스에 대해서는 공통의 행동을 구현. 전체 클래스에 속한 요소들을 관리하는 데 필요한 인터페이스를 정의한다. 순환 구조에서 요소들을 포함하는 전체 클래스로 접근하는 데 필요한 인터페이스를 정의하며, 적절하다면 그 인터페이스를 구현
  • Leaf: 가장 말단의 객체, 즉 자식이 없는 객체를 나타낸다. 객체 합성에 가장 기본이 되는 객체의 행동을 정의
  • Composite: 자식이 있는 구성요소에 대한 행동을 정의. 자신이 복합하는 요소들을 저장하면서, Component 인터페이스에 정의된 자식 관련 연산을 구현
  • Client: Component 인터페이스를 통해 복합 구조 내의 객체들을 조작

1. Product.java(Component)

public interface Product {
    int getPrice();
    String getCatalog();
}

 

2. Ramen.java, IceCream.java(Leaf)

public class IceCream implements Product{
    private int price;
    private String catalog;

    public IceCream(int price, String catalog){
        this.price = price;
        this.catalog = catalog;
    }

    @Override
    public String toString() {
        return "아이스크림";
    }

    @Override
    public int getPrice() {
        return price;
    }

    @Override
    public String getCatalog() {
        return catalog;
    }
}

 

public class Ramen implements Product{
    private int price;
    private String catalog;

    public Ramen(int price, String catalog){
        this.price = price;
        this.catalog = catalog;
    }

    @Override
    public String toString() {
        return "라면";
    }

    @Override
    public int getPrice() {
        return price;
    }

    @Override
    public String getCatalog() {
        return catalog;
    }
}

 

3. Basket.java (Composite)

import java.util.ArrayList;
import java.util.List;

public class Basket implements Product{
    private List<Product> items;

    public Basket(){
        this.items = new ArrayList<>();
    }

    public Basket(List<Product> items){
        this.items = items;
    }

    public boolean add(Product product){
        return items.add(product);
    }

    public boolean remove(Product product){
        return items.remove(product);
    }


    @Override
    public int getPrice() {
        return items.stream().mapToInt(Product::getPrice).sum();
    }

    @Override
    public String getCatalog() {
        return items.toString();
    }
}

 

 

4. Client.java

public class Client {
    public static void main(String[] args) {
        IceCream iceCream = new IceCream(1000,"빙과");
        Ramen ramen = new Ramen(1500,"면류");
        Basket basket = new Basket();
        basket.add(iceCream);
        basket.add(ramen);

        int totalPrice = basket.getPrice();
        String totalCatalog = basket.getCatalog();
        System.out.println("총 가격은 "+totalPrice+" 입니다.");
        System.out.println("카테고리 종류는 "+totalCatalog+" 입니다.");
    }
}

반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함