반응형
Notice
Recent Posts
Recent Comments
Link
250x250
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

동글이의 STORY

장식자 패턴 본문

Javascript/자바스크립트 패턴

장식자 패턴

dongling 2024. 7. 3. 21:55
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
반응형

'Javascript > 자바스크립트 패턴' 카테고리의 다른 글

전략 패턴  (1) 2024.07.03
샌드박스 패턴  (0) 2024.07.03
네임스페이스 패턴  (3) 2024.07.03
팩토리 패턴  (1) 2024.07.03
싱글톤 패턴  (0) 2024.07.03