06.07.2017 Views

Mastering JavaScript

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

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

Chapter 5<br />

The Node.js server will have something as follows:<br />

var nodeServer = new BasicServer();<br />

nodeServer = nodeServer.decorate('serveNode');<br />

nodeServer = nodeServer.decorate('3000');<br />

nodeServer.init();<br />

There are several ways in which the decorator pattern is implemented in <strong>JavaScript</strong>.<br />

We will discuss a method where the pattern is implemented by a list and does not<br />

rely on inheritance or method call chain:<br />

//Implement BasicServer that does the bare minimum<br />

function BasicServer() {<br />

this.pid = 1;<br />

console.log("Initializing basic Server");<br />

this.decorators_list = []; //Empty list of decorators<br />

}<br />

//List of all decorators<br />

BasicServer.decorators = {};<br />

//Add each decorator to the list of BasicServer's decorators<br />

//Each decorator in this list will be applied on the BasicServer<br />

instance<br />

BasicServer.decorators.reverseProxy = {<br />

init: function(pid) {<br />

console.log("Started Reverse Proxy");<br />

return pid + 1;<br />

}<br />

};<br />

BasicServer.decorators.servePHP = {<br />

init: function(pid) {<br />

console.log("Started serving PHP");<br />

return pid + 1;<br />

}<br />

};<br />

BasicServer.decorators.serveNode = {<br />

init: function(pid) {<br />

console.log("Started serving Node");<br />

return pid + 1;<br />

}<br />

};<br />

[ 135 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!