public
Description: Examples for javascriptkata.com
Homepage: http://www.javascriptkata.com
Clone URL: git://github.com/dsimard/jskata_examples.git
dsimard (author)
Mon Oct 05 07:36:30 -0700 2009
commit  a4240da8d85d09a1f8891eef172e486367fe3da9
tree    7ce974aa97627afd9af5676d69409085e87e5ef6
parent  1719f0731a14cf252565fe20315cc4e3b300f0bf
jskata_examples / singleton / singleton.js
100644 47 lines (39 sloc) 1.23 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
function Cats() {
var names = [];
 
this.singletonInstance = null;
 
// Get the instance of the Cats class
// If there's none, instanciate one
var getInstance = function() {
if (!this.singletonInstance) {
this.singletonInstance = createInstance();
}
return this.singletonInstance;
}
 
// Create an instance of the Cats class
var createInstance = function() {
// Here, you return all public methods and variables
return {
add : function(name) {
names.push(name);
return this.names();
},
names : function() {
return names;
}
}
}
 
return getInstance();
}
 
function run() {
// Add a new cat
var cat1 = new Cats();
cat1.add("Mistigri");
jsKataEx.assert(cat1.names().length == 1, "cat1 contains 1 cat : " + cat1.names().toString());
 
// Use another instance
var cat2 = new Cats();
jsKataEx.assert(cat2.names().length == 1, "cat2 contains Mistigri added in cat1 : " + cat2.names().toString());
 
// Add another cat in the other instance
cat2.add("Felix");
jsKataEx.assert(cat2.names().length == 2, "cat2 contains Mistigri and Felix" + cat2.names().toString());
jsKataEx.assert(cat2.names().length == 2, "cat1 also contains Mistigri and Felix" + cat1.names().toString());
}