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.

38<br />

CHAPTER 3 ■ ENCAPSULATION AND INFORMATION HIDING<br />

// Privileged static method.<br />

this.getUPPER_BOUND() {<br />

return UPPER_BOUND;<br />

}<br />

...<br />

// Return the constructor.<br />

return function(constructorArgument) {<br />

...<br />

}<br />

})();<br />

If you have a lot of constants and don’t want to create an accessor method for each, you<br />

can create a single generic accessor method:<br />

var Class = (function() {<br />

// Private static attributes.<br />

var constants = {<br />

UPPER_BOUND: 100,<br />

LOWER_BOUND: -100<br />

}<br />

// Privileged static method.<br />

this.getConstant(name) {<br />

return constants[name];<br />

}<br />

...<br />

// Return the constructor.<br />

return function(constructorArgument) {<br />

...<br />

}<br />

})();<br />

Then you would get a constant by calling the single accessor:<br />

Class.getConstant('UPPER_BOUND');<br />

Singletons and Object Factories<br />

There are other patterns that utilize closures to create a protected variable space. The two that<br />

rely on it the most are the singleton pattern and the factory pattern. Both are covered in more<br />

detail later in the book, but we mention them here because they use these same concepts to<br />

hide information.<br />

The singleton pattern uses a returned object literal to expose privileged members, while<br />

keeping private members protected in the enclosing function’s scope. It uses the same technique<br />

that we covered earlier, where an outer function is executed immediately and the result

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

Saved successfully!

Ooh no, something went wrong!