728x90
반응형
Composite Pattern
그룹 전체와 개별 객체를 동일하게 처리할 수 있는 패턴
클라이언트 입장에서 '전체'나 '부분'이나 모두 동일한 컴포넌트로 인식할 수 있는 계층 구조를 만든다(Part-Whole Hierarchy)
그룹 전체와 개별 객체를 동일하게 처리할 수 있는 패턴.
Client
- Item과 Bag은 Component를 상속받고 Client를 생성할 때 Component를 주입하여 해당 가격을 구한다.
public class Client {
public static void main(String[] args) {
Item doranBlade = new Item("도란검", 450);
Item healPotion = new Item("체력 물약", 50);
Bag bag = new Bag();
bag.add(doranBlade);
bag.add(healPotion);
Client client = new Client();
client.printPrice(doranBlade);
client.printPrice(bag);
}
private void printPrice(Component component) {
System.out.println(component.getPrice());
}
}
Component
public interface Component {
int getPrice();
}
Item & Bag
- Bag의 리스트 타입은 Item이 아니라 Component가 되어야 한다.
public class Item implements Component {
private String name;
private int price;
public Item(String name, int price) {
this.name = name;
this.price = price;
}
@Override
public int getPrice() {
return this.price;
}
}
public class Bag implements Component {
private List<Component> components = new ArrayList<>();
public void add(Component component) {
components.add(component);
}
public List<Component> getComponents() {
return components;
}
@Override
public int getPrice() {
return components.stream().mapToInt(Component::getPrice).sum();
}
}
[패턴 복습]
장점 | 단점 |
- 복잡한 트리구조를 편리하게 사용 - 다형성과 재귀 활용 가능 - 클라이언트 코드를 변경하지 않고 새로운 엘리먼트 타입을 추가할 수 있다. (클라리언트는 구체적인 정보를 알 필요가 없다.) |
- 트리를 만들어야 하기 때문에 (공통된 인터페이스를 정의해야 하기 때문에) 지나치게 일반화 해야 하는 경우도 생길 수 있다. |
[실무에서 쓰이는 경우]
- 자바
- Swing 라이브러리
- JSF(JavaServer Faces) 라이브러리
728x90
반응형
'Design Patterns > 구조(Structural)' 카테고리의 다른 글
[Flyweight]플라이웨이트패턴 (0) | 2022.10.18 |
---|---|
[Facade]퍼사드패턴 (0) | 2022.10.18 |
[Decorator]데코레이터패턴 (0) | 2022.08.01 |
[Bridge]브릿지패턴 (0) | 2022.08.01 |
[Adaptor]어댑터패턴 (0) | 2022.05.31 |