프런트엔드/디자인 패턴

[4일차] 데코레이터 | 구조 패턴 7일만에 끝내기 챌린지 - GoF 디자인 패턴

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

 

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

 

 

[4일차] 데코레이터(Decorator)
구조 패턴 7일만에 끝내기 챌린지 - GoF 디자인 패턴

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

 

 

데코레이터란?

객체에 동적으로 새로운 책임을 추가할 수 있게 합니다.
기능을 추가할 때 서브클래스를 생성하는 것보다 융통성 있는 방법을 제공합니다.

 

 

활용성

1) 다른 객체에 영향을 주지 않고 각각의 객체에
새로운 책임을 추가하기 위해 사용합니다.


2) 제거 될 수 있는 책임에 대해 사용합니다.


3) 너무 많은 수의 독립된 확장이 가능할 때
모든 조합을 지원하기 위해 상속으로 해결하면
클래스 수가 폭발적으로 많아지므로 실제 상속으로 서브클래스를 계속 만드는 방법이
실질적이지 못할 때 사용합니다.

 

 

구조 및 구현

(1) 인터페이스 일치 시키기
반드시 자신을 둘러싼 구성 요소의 인터페이스를 만족해야 한다.

(2) Component 클래스는 가벼운 무게를 유지하기

가볍게 정의한다는 의미는

연산에 해당하는 인터페이스만을 정의하고

무언가 저장할 수 있는 변수는 정의하지 말라는 의미다.

interface Component {
    operation(): void
}

class ConcreteComponent implements Component {
    operation() {
        console.log('ConcreteComponent.operation')
    }
}

abstract class Decorator implements Component {
    component: Component
    constructor (component: Component) {
        this.component = component
    }
    operation() {
        component.operation()
    }
}

class ConcreteDecorator extends Decorator {
    constructor(component: Component) {
        super(component)
    }
    operation() {
        super.operation()
        this.addedBehavior()
    }
    addedBehavior() {
        console.log('ConcreteDecorator.addedBehavior')
    }
}
 
class Main {
    component: Component
    constructor() {
        this.component = new ConcreteComponent()
        this.component.operation()
        // ConcreteComponent.operation
    }
}

// Decorator 사용
class Main {
    component: Component
    constructor() {
        const concreteComponent = new ConcreteComponent()
        this.component = new ConcreteDecorator(component)
        this.component.operation()
        // ConcreteComponent.operation
        // ConcreteDecorator.addedBehavior
    }
}
 

 

 


728x90