Architecture
[GOF] 컴포지트 패턴
개 발자국
2021. 10. 31. 16:03
컴포지트 패턴
활용 : 객체들의 관계를 트리구조로써 부분 전체 계층을 표현하는 패턴으로 사용자가 단일 객체 복합 객들도 모두 동일하게 다룰 수 있도록 할 때 사용 한다.
객체 구성
- Component : 인터페이스를 정의하며, 컴포지트 객체에 대한 기본 동작을 구현한다.
Leaf 와 Composite가 구현해야 하는 interface이며, 이 두 요소는 상황에 따라 개별적인 클래스가 아닌 Component 인터페이스로 다루어 진다.
- Composite : Leaf 혹은 Composite 인스턴스를 자식으로 가진다.
- Leaf : Composite의 자식의 역할을 하며, 이 노드가 Compsite를 자식으로 두지 않는다.
책의 카테고리라는 구성으로 본 Composite 패턴 .
카테고리 : 카테고리는 책을 포함 할 수도 있고, 카테고리를 하위 자식으로 설정이 가능하다. 즉 Component interface를 구현한 클래스는 모두 자식으로 받아 드릴 수 있다.
책 : 책은 그 어떤 자식도 가질 수 없다. 책은 카테고리에 종속적이기에 부모가 필수요소이다.
컴포넌트 : 책과 카테고리를 한개의 인터페이스로 엮는 역할이다.
컴포넌트
// Component
interface ComponentInterface {
id: string
description: string
parent: ComponentInterface | null
getParent: () => ComponentInterface | null
}
** 책 **
class Book implements ComponentInterface {
constructor(
public id: string,
public description: string,
public parent: ComponentInterface
) { }
getParent() : ComponentInterface{
return this.parent
}
}
카테고리
class Category implements ComponentInterface {
children: ComponentInterface[] = []
constructor(
public id: string,
public description: string,
public parent: ComponentInterface | null
) { }
add(component: ComponentInterface) {
this.children.push(component)
}
remove(id: string) {
if (this.children.length == 0) { return }
const index = this.children.findIndex((component) => component.id == id);
if (index != -1) {
this.children.splice(index, 1)
} else {
this.children.forEach((e) => {
if (e instanceof Category) {
e.remove(id)
}
})
}
}
getParent() : ComponentInterface | null {
return this.parent
}
}
장점 과 단점
장점 : 컴포넌트 인터페이스를 구현한다면 새로운 클래스의 추가가 용이하다.
단점 : 한개의 인터페이스로 객체를 취급하기 때문에 객체간 구별이 어렵다.
반응형