03.09.2015 Views

Design Patterns

Download - Assembla

Download - Assembla

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

198<br />

CHAPTER 14 ■ THE PROXY PATTERN<br />

/* PublicLibrary class. */<br />

var PublicLibrary = function(books) { // implements Library<br />

this.catalog = {};<br />

for(var i = 0, len = books.length; i < len; i++) {<br />

this.catalog[books[i].getIsbn()] = { book: books[i], available: true };<br />

}<br />

};<br />

PublicLibrary.prototype = {<br />

findBooks: function(searchString) {<br />

var results = [];<br />

for(var isbn in this.catalog) {<br />

if(!this.catalog.hasOwnProperty(isbn)) continue;<br />

if(searchString.match(this.catalog[isbn].getTitle()) ||<br />

searchString.match(this.catalog[isbn].getAuthor())) {<br />

results.push(this.catalog[isbn]);<br />

}<br />

}<br />

return results;<br />

},<br />

checkoutBook: function(book) {<br />

var isbn = book.getIsbn();<br />

if(this.catalog[isbn]) {<br />

if(this.catalog[isbn].available) {<br />

this.catalog[isbn].available = false;<br />

return this.catalog[isbn];<br />

}<br />

else {<br />

throw new Error('PublicLibrary: book ' + book.getTitle() +<br />

' is not currently available.');<br />

}<br />

}<br />

else {<br />

throw new Error('PublicLibrary: book ' + book.getTitle() + ' not found.');<br />

}<br />

},<br />

returnBook: function(book) {<br />

var isbn = book.getIsbn();<br />

if(this.catalog[isbn]) {<br />

this.catalog[isbn].available = true;<br />

}<br />

else {<br />

throw new Error('PublicLibrary: book ' + book.getTitle() + ' not found.');<br />

}<br />

}<br />

};

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!