You are on page 1of 2

http://addyosmani.

com/resources/essentialjsdesignpatterns/book/

A Basic Factory
Let's now define a very basic factory. What we're going to have it do is perform a
check to see if a book with a particular title has been previously created inside the
system; if it has, we'll return it - if not, a new book will be created and stored so that
it can be accessed later. This makes sure that we only create a single copy of each
unique intrinsic piece of data:
?

// Book Factory singleton

var BookFactory = (function () {

var existingBooks = {}, existingBook;

4
5
6

return {
createBook: function ( title, author, genre, pageCount, publisherID, ISBN ) {

7
8
9
10
11
12

// Find out if a particular book meta-data combination has been created before
// !! or (bang bang) forces a boolean to be returned
existingBook = existingBooks[ISBN];
if ( !!existingBook ) {
return existingBook;
} else {

13
14
15
16

// if not, let's create a new instance of the book and store it


var book = new Book( title, author, genre, pageCount, publisherID, ISBN );
existingBooks[ISBN] = book;

17
return book;

18
19
}

20
}

21

};

22
23
24

});

You might also like