Friday, July 27, 2007

Singleton Factory

source : http://www.bigroom.co.uk/blog/singleton-factory/

== quote ==
package { 

function
Singleton( c:Class ):*
{

for
( var i:String in instances )
{

if
( instances[i].constructor === c )
{

return
instances[i];
}
}


var
obj:* = new c();
instances.push( obj );

return
obj;
}
}

var
instances:Array = new Array();




You can use this function to create an instance of any class (your own or an intrinsic class) as follows (for example):

import flash.geom.Point;
var a:Point = Singleton( Point );

In the comments below, Benny suggested a good improvement to gain a more stable lookup time by using a Dictionary instead of an Array. His suggestion, with minor alterations by me, looks like this.

package {
function Singleton( c:Class ):*
{ return c in instances ? instances[c] : in[c] = new c();
}
}

import flash.utils.Dictionary;
var instances:Dictionary = new Dictionary( false );

No comments: