Oct 10 2008

4

Mootools Singleton Class Mutator

Category: MutatorTags: , ,

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.

Tags: , ,