Permalink
Browse files

Merge pull request #69 from beaufortfrancois/1.5.2

Updated singleton pattern example
  • Loading branch information...
2 parents 37e41ae + 4e1e17e commit 42a5bd456e6ecaf8c78a768d33b6df62eaabb0ca @addyosmani committed Jan 22, 2013
Showing with 49 additions and 2 deletions.
  1. +49 −2 book/index.html
View
@@ -1478,14 +1478,21 @@ <h2 id="singletonpatternjavascript">
var privateVariable = "Im also private";
+ var privateRandomNumber = Math.random();
+
return {
// Public methods and variables
publicMethod: function () {
console.log( "The public can see me!" );
},
- publicProperty: "I am also public"
+ publicProperty: "I am also public",
+
+ getRandomNumber: function() {
+ return privateRandomNumber;
+ }
+
};
};
@@ -1507,11 +1514,51 @@ <h2 id="singletonpatternjavascript">
})();
+var myBadSingleton = (function () {
+
+ // Instance stores a reference to the Singleton
+ var instance;
+
+ function init() {
+
+ // Singleton
+
+ var privateRandomNumber = Math.random();
+
+ return {
+
+ getRandomNumber: function() {
+ return privateRandomNumber;
+ }
+
+ };
+
+ };
+
+ return {
+
+ // Always create a new Singleton instance
+ getInstance: function () {
+
+ instance = init();
+
+ return instance;
+ }
+
+ };
+
+})();
+
+
// Usage:
var singleA = mySingleton.getInstance();
var singleB = mySingleton.getInstance();
-console.log( singleA === singleB ); // true
+console.log( singleA.getRandomNumber() === singleB.getRandomNumber() ); // true
+
+var badSingleA = myBadSingleton.getInstance();
+var badSingleB = myBadSingleton.getInstance();
+console.log( badSingleA.getRandomNumber() !== badSingleB.getRandomNumber() ); // true
</pre>
<p>What makes the Singleton is the global access to the instance (generally through <code>MySingleton.getInstance()</code>) as we don't (at least in static languages) call <code>new MySingleton()</code> directly. This is however possible in JavaScript.</p>

0 comments on commit 42a5bd4

Please sign in to comment.