디자인 패턴 - 구조 패턴(복합체)
복합체(Composite) 패턴
객체 구조를 순회할수 있는 구조(트리구조)로 구성하여, 개별 작업을 진행할수 있게 하는 구조입니다.
실제 적용 예시
- 군대같은 곳은 상하관계 계층구조로 설계되어 있어 순회하면서 명확한 업무지시를 한다.
export interface Component {
operation(): void;
}
export class Composite implements Component {
private list: Component[];
private s: String;
constructor(s: String) {
this.list = [];
this.s = s;
}
public operation(): void {
console.log("`operation of `", this.s)
for (var i = 0; i < this.list.length; i += 1) {
this.list[i].operation();
}
}
public add(c: Component): void {
this.list.push(c);
}
public remove(i: number): void {
if (this.list.length <= i) {
throw new Error("index out of bound!");
}
this.list.splice(i, 1);
}
}
export class Leaf implements Component {
private s: String;
constructor(s: String) {
this.s = s;
}
public operation(): void {
console.log("`operation` of Leaf", this.s, " is called.");
}
}
const leaf1 = new CompositePattern.Leaf("1");
const leaf2 = new CompositePattern.Leaf("2");
const leaf3 = new CompositePattern.Leaf("3");
const composite1 = new CompositePattern.Composite("Comp1");
const composite2 = new CompositePattern.Composite("Comp2");
composite1.add(leaf1);
composite1.add(leaf2);
composite1.add(leaf3);
composite1.remove(2);
composite2.add(leaf1);
composite2.add(leaf3);
composite1.operation();
composite2.operation();
언제 사용할까 ?
복합체 클래스 요소들이 같은 인터페이스를 공유하여, 순회하며 같은 작업을 하거나, 알맞은 작업의 요소까지 찾아가는등의 과정에서 좋은 패턴입니다.
장점
- 재귀를 편하게 해준다.
- 객체 트리를 회손하지 않는다.
단점
- 기능이 너무 다른 객체 끼리 복합체 형성은 어려울수 있다. 이럴 경우 너무 인터페이스가 일반화 될수 있어, 어떤 기능인지 이해하기 어려울 수 있다.