I got really excited about Class Mutators within Mootools after reading Jan Kassens blog. If you have ever used Mootools, you have probably seen the standard Mutators. Extends and Implements. These allow you to augment your Classes to help create an inheritance model within Mootools. What I failed to realize is that Mutators goes well beyond that. They have the ability to ‘morph’ your Classes to make your code easier to read and maintain.
I went ahead and implemented the Singleton pattern into Mootools classes.
Class.Mutators.Singleton = function(self,flag){ if(!flag) return; self.constructor.__instance = undefined; if($defined(self.initialize) && $type(self.initialize) == 'function') var init = self.initialize; self.initialize = function(){ if(!$defined(this.constructor.__instance)){ if($defined(init) && $type(init) == 'function') init.apply(this,arguments); this.constructor.__instance = this; } return this.constructor.__instance; } }
Use:
var Counter = new Class({ Singleton : true, initialize : function(){ this.count = 0; }, hit : function(){ return ++this.count; } }); var a = new Counter(); a.hit(); // returns 1 a.hit(); // return 2 var b = new Counter(); b.hit(); // return 3 !!!
Honestly, this is more for the OO purist out there. I would have to agree with Valerio that the best way to implement a singleton in javascript is to use a basic object. However, I do think that this could be useful in rare occasions.
October 10th, 2008 at 12:27 pm
This pattern is called the “Borg” pattern, not “Singleton”, though it behvaes pretty much exactly like a singleton
October 10th, 2008 at 12:28 pm
nice nice nice!
Well done man!
December 4th, 2008 at 12:18 pm
[...] my actual production code I had my Registry class implement my Singleton Class Mutator. This way I could initialize the registry object multiple times in my code without the need to [...]
March 6th, 2009 at 3:56 am
This is awesome, thanks a lot.