Created
July 1, 2018 17:59
-
-
Save drenther/884594ca2921c9396a89783e96877e21 to your computer and use it in GitHub Desktop.
Structural Pattern - Decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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