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.

CHAPTER 3 ■ ENCAPSULATION AND INFORMATION HIDING 35<br />

object is instantiated. This has the potential to use more memory than the other patterns, so it<br />

should only be used when you require true private members. This pattern is also hard to subclass.<br />

The new inherited class will not have access to any of the superclass’s private attributes or methods.<br />

It is said that “inheritance breaks encapsulation” because in most languages, the subclass has<br />

access to all of the private attributes and methods of the superclass. In JavaScript, this is not the<br />

case. If you are creating a class that might be subclassed later, it is best to stick to one of the fully<br />

exposed patterns.<br />

More Advanced <strong>Patterns</strong><br />

Now that you have three basic patterns at your disposal, we’ll show you a few advanced patterns.<br />

Part 2 of this book goes into much more detail about specific patterns, but we will take<br />

an introductory look at a few of them here.<br />

Static Methods and Attributes<br />

Applying the lesson of scope and closures from earlier in the chapter can lead to a way to<br />

create static members, which can be both private and publicly accessible. Most methods<br />

and attributes interact with an instance of a class; static members interact with the class<br />

itself. Another way of putting it is to say that static members operate on the class-level instead<br />

of the instance-level; there is only one copy of each static member. As you will see later in<br />

this section, static members are called directly off of the class object.<br />

Here is the Book class with static attributes and methods:<br />

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

// Private static attributes.<br />

var numOfBooks = 0;<br />

// Private static method.<br />

function checkIsbn(isbn) {<br />

...<br />

}<br />

// Return the constructor.<br />

return function(newIsbn, newTitle, newAuthor) { // implements Publication<br />

// Private attributes.<br />

var isbn, title, author;<br />

// Privileged methods.<br />

this.getIsbn = function() {<br />

return isbn;<br />

};<br />

this.setIsbn = function(newIsbn) {<br />

if(!checkIsbn(newIsbn)) throw new Error('Book: Invalid ISBN.');<br />

isbn = newIsbn;<br />

};

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

Saved successfully!

Ooh no, something went wrong!