동글이의 STORY
장식자 패턴 본문
728x90
반응형
🔶 장식자 패턴(Decorator pattern)
- 객체에 동적으로 새로운 행위를 추가할 수 있도록 해주는 구조 패턴
- 동작이나 기능을 동적으로 추가하는데 초첨을 둔 것
장점
- 서브 클래스에 의전할 필요 없음
- 객체는 새로운 행동에 유연하게 사용될 수 있으며 본 객체를 계속 사용할 수 있다.
단점
- 관리가 되지 않으면 아키텍처가 복잡해 질 수 있다.
🔹 예시 코드
class Book {
constructor(title, author, price) {
this._title = title;
this._author = author;
this.price = price;
}
getDetails() {
return `${this._title} by ${this._author}`;
}
}
// decorator 1
function giftWrap(book) {
book.isGiftWrapped = true;
book.unwrap = function() {
return `Unwrapped ${book.getDetails()}`;
};
return book;
}
// decorator 2
function hardbindBook(book) {
book.isHardbound = true;
book.price += 5;
return book;
}
// usage
const alchemist = giftWrap(new Book('The Alchemist', 'Paulo Coelho', 10));
console.log(alchemist.isGiftWrapped); // true
console.log(alchemist.unwrap()); // 'Unwrapped The Alchemist by Paulo Coelho'
console.log(alchemist.getDetails()); // 'The Alchemist by Paulo Coelho'
console.log(alchemist.price); // 10
const inferno = hardbindBook(new Book('Inferno', 'Dan Brown', 15));
console.log(inferno.isHardbound); // true
console.log(inferno.price); // 20
- Book 클래스를 생성한다. 그리고 나서 2개의 decorator 함수를 생성
- 이 함수들은 각각 book 객체를 받고 "decorated” book 객체로 반환
728x90
반응형