03.09.2015 Views

Design Patterns

Download - Assembla

Download - Assembla

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 7 ■ THE FACTORY PATTERN 103<br />

extend(OfflineHandler, SimpleHandler);<br />

OfflineHandler.prototype.request = function(method, url, callback, postVars) {<br />

if(XhrManager.isOffline()) { // Store the requests until we are online.<br />

this.storedRequests.push({<br />

method: method,<br />

url: url,<br />

callback: callback,<br />

postVars: postVars<br />

});<br />

}<br />

else { // Call SimpleHandler's request method if we are online.<br />

this.flushStoredRequests();<br />

OfflineHandler.superclass.request(method, url, callback, postVars);<br />

}<br />

};<br />

OfflineHandler.prototype.flushStoredRequests = function() {<br />

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

var req = storedRequests[i];<br />

OfflineHandler.superclass.request(req.method, req.url, req.callback,<br />

req.postVars);<br />

}<br />

};<br />

OfflineHandler is a little simpler. Using the XhrMananger.isOffline method (which we will<br />

talk more about in a moment), it ensures that the user is online before allowing the request to<br />

be made, through SimpleHandler’s request method. It also executes all stored requests as soon<br />

as it detects that the user is online.<br />

Choosing Connection Objects at Run-Time<br />

Here is where the factory pattern comes into play. Instead of requiring the programmer to<br />

choose among these different classes at development time, when they have absolutely no idea<br />

what the network conditions will be for any of the end users, you use a factory to choose the<br />

most appropriate class at run-time. The programmer simply calls the factory method and uses<br />

the object that gets returned. Since all of these handlers implement the AjaxHandler interface,<br />

you can treat them identically. The interface remains the same; only the implementation changes:<br />

/* XhrManager singleton. */<br />

var XhrManager = {<br />

createXhrHandler: function() {<br />

var xhr;<br />

if(this.isOffline()) {<br />

xhr = new OfflineHandler();<br />

}<br />

else if(this.isHighLatency()) {<br />

xhr = new QueuedHandler();<br />

}

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

Saved successfully!

Ooh no, something went wrong!