프런트엔드/디자인 패턴

[3일차] 컴포지트 | 구조 패턴 7일만에 끝내기 챌린지 - GoF 디자인 패턴

조드래곤나인 2023. 7. 16. 14:49

 

출처: 에릭 감마 , 리처드 헬름 , 랄프 존슨 , 존 블리시디스. 『Gof의 디자인 패턴』. 김정아(역). 프로텍미디어, 2015.

 

 

[3일차] 컴포지트(Composite)
구조 패턴 7일만에 끝내기 챌린지 - GoF 디자인 패턴

타입스크립트로 설명하는 GoF 디자인 패턴의 구조 패턴 7일만에 끝내기 챌린지

 

 

컴포지트란?

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

 

 

활용성

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

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

 

 

구조 및 구현

interface Component {
    operation(): void
    add?(component: Component): void
    remove?(component: Component): void
    getChild?(num: number): Component
}

class Leaf implements Component {
    operation() {}
}

class Composite implements Component {
    private children: Component[] = []
    operation() {}
    add(component: Component) {
        this.children.push(component)
    }
    remove(component: Component) {
        const index = this.children.indexOf(component)
        if (index > -1) {        
           this.children.splice(index, 1)
        }
    }
    getChild (num: number) {
        return this.children[num]
    }
}
 
class Main {
    constructor () {
        const root = new Composite()
        const parent = new Composite()

        root.add(new Leaf())
        root.add(new Leaf())
        root.add(parent)

        parent.add(new Leaf())

        console.log(root)
        // Composite
        //     children: Array(3)
        //         0: Leaf
        //         1: Leaf
        //         2: Composite
        //             children: Array(1)
        //                 0: Leaf
    }
}
 

 


728x90