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.

252<br />

CHAPTER 17 ■ THE CHAIN OF RESPONSIBILITY PATTERN<br />

var responseObject = this.firstGenreCatalog.findBooks(requestObject);<br />

return responseObject.results;<br />

}<br />

// Otherwise, search through all books.<br />

else {<br />

var results = [];<br />

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

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

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

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

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

}<br />

}<br />

return results;<br />

}<br />

},<br />

checkoutBook: function(book) { ... },<br />

returnBook: function(book) { ... },<br />

addBook: function(newBook) { ... }<br />

};<br />

The findBooks method creates an object that encapsulates all of the information regarding<br />

the request, including a list of the genres to search, the search terms, and an empty array<br />

to hold any results that are found. The obvious question is, why bother to create this object<br />

when you could just as easily pass these pieces of information as separate arguments? You create<br />

the object mostly because it is much easier to keep track of all the data if it is in a single place.<br />

You need to keep this information intact through all of the links in the chain, and encapsulating<br />

it in a single object makes it easier to do that. In this example, you will pass this same object<br />

back to the client as the response. This helps in keeping the results together with the terms<br />

and genres you are searching through, in the event that you fire off more than one search<br />

through the chain at a time.<br />

You will now implement the findBooks method in the GenreCatalog superclass. This method<br />

is used by all subclasses and shouldn’t need to be overridden. The code is a bit complex, so we<br />

will go through it line by line:<br />

/* GenreCatalog class, used as a superclass for specific catalog classes. */<br />

var GenreCatalog = function() { // implements Catalog<br />

this.successor = null;<br />

this.catalog = [];<br />

this.genreNames = [];<br />

};<br />

GenreCatalog.prototype = {<br />

_bookMatchesCriteria: function(book) { ... }<br />

handleFilingRequest: function(book) { ... },<br />

findBooks: function(request) {<br />

var found = false;<br />

for(var i = 0, len = request.genres.length; i < len; i++) {

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

Saved successfully!

Ooh no, something went wrong!