1. 의도
객체들의 관계를 트리 구조로 구성해 부분 - 전체 계층을 표현하는 패턴으로 사용자가 단일 객체와 복합 객체 모두 동일하게 다루도록 한다.
2. 용도
복합 객체와 단일 객체의 처리 방법이 다르지 않을 경우, 전체 - 부분 관계로 정의할 수 있다.
전체 - 부분 관계의 대표적 예는 directory - file 이 존재한다.
이러한 전체 - 부분 관계를 효율적으로 정의할 때 유용하다.
3. UML
4. 구현
public interface IItemComponent {
int getPrice();
String getName();
}
===============================================================
public class Bag implements IItemComponent{
private final String name;
List<IItemComponent> components;
public Bag(String name) {
this.name = name;
this.components = new ArrayList<>();
}
public void add(IItemComponent component) {
components.add(component);
}
@Override
public int getPrice() {
return components.stream().mapToInt(IItemComponent::getPrice).sum();
}
@Override
public String getName() {
return this.name;
}
}
===============================================================
public class Item implements IItemComponent {
private final String name;
private final int price;
public Item(String name, int price) {
this.name = name;
this.price = price;
}
@Override
public int getPrice() {
return this.price;
}
@Override
public String getName() {
return this.name;
}
}
===============================================================
public class Client {
public static void main(String[] args) {
Bag mainBag = new Bag("Main bag");
Item armor = new Item("Armor", 250);
Item sword = new Item("Sword", 500);
mainBag.add(armor);
mainBag.add(sword);
Bag foodBag = new Bag("Food bag");
Item apple = new Item("Apple", 20);
Item banana = new Item("Banana", 10);
foodBag.add(apple);
foodBag.add(banana);
mainBag.add(foodBag);
System.out.println("Main bag price: " + mainBag.getPrice());
System.out.println("Food bag price: " + foodBag.getPrice());
}
}
//Main bag price: 780
//Food bag price: 30
5. 패턴의 장단점
- 장점
- 복잡한 트리 구조를 편리하게 사용할 수 있다.
- 다형성과 재귀를 활용할 수 있다.
- 클라이언트 코드를 변경하지 않고, component의 집합인 composite도 이용할 수 있다.
- 단점
- 트리 자료구조가 어울리는 경우엔 자연스럽게 사용 할 수 있지만 어울리지 않는 경우엔 지나치게 일반화해야 할 수도 있다.
출처 :
https://refactoring.guru/design-patterns/composite
Composite
/ Design Patterns / Structural Patterns Composite Also known as: Object Tree Intent Composite is a structural design pattern that lets you compose objects into tree structures and then work with these structures as if they were individual objects. Problem
refactoring.guru
'디자인 패턴' 카테고리의 다른 글
자바(JAVA) - 팩토리 메서드(Factory Method) 패턴 (0) | 2023.11.15 |
---|---|
자바(JAVA) - 추상팩토리(Abstract Factory) 패턴 (2) | 2023.11.08 |
자바(JAVA) - 커맨드(Command) 패턴 (0) | 2023.11.01 |
자바(JAVA) - 데코레이터(Decorator) 패턴 (0) | 2023.10.19 |
자바(JAVA) - 빌더(Builder) 패턴 (0) | 2023.10.18 |