Permalink
Browse files

Added Bad Singleton Example

  • Loading branch information...
wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww committed Jan 22, 2013
1 parent 7e6d70b commit 4e1e17e6427148b7d0b45581f4eedfbd33442855
Showing with 40 additions and 0 deletions.
  1. +40 −0 book/index.html
View
@@ -1514,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.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 4e1e17e

Please sign in to comment.