Skip to content

Instantly share code, notes, and snippets.

@drenther
Created July 1, 2018 17:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drenther/884594ca2921c9396a89783e96877e21 to your computer and use it in GitHub Desktop.
Save drenther/884594ca2921c9396a89783e96877e21 to your computer and use it in GitHub Desktop.
Structural Pattern - Decorator
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'
const inferno = hardbindBook(new Book('Inferno', 'Dan Brown', 15));
console.log(inferno.isHardbound); // true
console.log(inferno.price); // 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment