디자인 패턴 - Decoration

Jaa-van·2023년 6월 1일
0
post-thumbnail

상황에 따라 어떤 객체에 책임을 덧붙이는 패턴

상황에 따라 어떠한 특성 혹은 행동을 덧붙이는 패턴을 데코레이터 패턴


function drinks() {
    this.cost = 0
}

function bear(drinks) {
    drinks.cost = drinks.cost + 4000,
    drinks.bear = 500ml,
    return drinks
}

function soju(drinks) {
    drinks.cost = drinks.cost + 4000,
    drinks.soju = 1,
    return drinks
}

function vodka (drinks) {
    drinks.cost = drinks.cost + 15000,
    drinks.vodka = 1,
    return drinks
}

let alcohol = new drinks()
let somack = soju(bear(alcohol))
let vomack = vodka(bear(alcohol))

console.log(somack.soju, somack.bear, somack.cost) // 1, 500, 8000

drinks 를 사용하는 코드를 훼손하지 않으면서 런타임에 추가 행동들을 객체에게 할당할 수 있게 해야한다.


function drinks() {
    this.cost = 2000
} // 2000원이라는 자릿세를 추가한다고 생각해보자

모든 객체의 this.cost 에 2000원이 추가되는 것을 볼 수 있다.

class Animal {
    constructor(name) {
        this.name = name,
        this.speed = 0
    }
    run(speed) {
        this.speed = speed
        console.log(`${ this.name}이${this.speed}로 달린다`)
    }
}

let animal = new Animal("동물")

// Animal.prototype

// Rabbit.prototype
// constructor : Rabbit,
// boom : function

let rabbit = new Rabbit('폭발 토끼')

console.log(rabbit.boom()) // 폭발 토끼가 폭발했습니다
console.log(rabbit.run(1)) // 폭발 토끼이 1로 달린다








0개의 댓글