Last active
April 8, 2016 07:29
-
-
Save codejets/85fbeb6d9ea1598a6a29 to your computer and use it in GitHub Desktop.
Decorators Pattern using Books eStore
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
// Decorators Pattern | |
/* | |
We will create a Book Object with constructor to initialize Name, | |
Author, Ratings and Cost. | |
Then we will add decorators to add feature to the Book object for | |
some Ebooks. | |
*/ | |
(function() { | |
'use strict'; | |
// Creating the constructor to decorate | |
function Book(name, author, cost) { | |
this.name = name; | |
this.author = author; | |
this.cost = cost; | |
this.ratings = []; | |
} | |
// Pushing methods to the prototype | |
Book.prototype.addRating = function(rating) { | |
this.ratings.push(rating); | |
this.rating = this.ratings.reduce(function (p, c) { | |
return p + c; | |
}) / this.ratings.length; | |
console.log('Average Rating: ' + this.rating ) | |
}; | |
Book.prototype.buy = function() { | |
// Payment Routing | |
console.log('Thank you for your order!') | |
}; | |
var LOTR = new Book('LOTR', 'Tolkien', '1550'); | |
LOTR.addRating(3); // Average Rating: 3 | |
LOTR.addRating(5); // Average Rating: 4 | |
LOTR.addRating(5); // Average Rating: 4.333333333333333 | |
LOTR.addRating(4); // Average Rating: 4.25 | |
console.log(LOTR.rating); // 4.25 | |
LOTR.buy(); // Thank you for your order! | |
var eBook = function(name, author, cost) { | |
// Calling Book obj with name | |
Book.call(this, name); | |
this.author = author; | |
this.cost = cost; | |
this.ratings = []; | |
} | |
/* | |
We will use object.create to make a new object from Book's | |
prototype to our eBook's prototype so that we dont overwrite | |
Book's prototype. | |
*/ | |
eBook.prototype = Object.create(Book.prototype); | |
eBook.prototype.buy = function() { | |
console.log('Downloading Ebook...'); | |
Book.prototype.buy.call(this); | |
}; | |
var HarryPotterEBook = new eBook('HP', 'Rowling', '3550'); | |
HarryPotterEBook.addRating(3); // Average Rating: 3 | |
HarryPotterEBook.addRating(5); // Average Rating: 4 | |
HarryPotterEBook.addRating(5); // Average Rating: 4.33 | |
HarryPotterEBook.addRating(4); // Average Rating: 4.25 | |
console.log(HarryPotterEBook.rating); // 4.25 | |
HarryPotterEBook.buy(); | |
/* Downloading Ebook... | |
Thank you for your order! */ | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment