AS * Factory
Too often do I find myself writing code that looks something like the following.
var spr:Sprite = new Sprite();
spr.x = 20;
spr.y = 100;
spr.alpha = 0.5;
spr.rotation = 15;
Some programming languages like Python support “named parameters”. This can be emulated in Actionscript using the following technique. Ruby often uses a similar technique by having a single hash as a parameter to a constructor.
package com.roddeh.utils{
public class Factory{
public static function create(clazz:Class, properties:Object):*{
try{
var object:* = new clazz();
}
catch(e:Error){}
for(var ind:String in properties){
try{
object[ind] = properties[ind];
}
catch(e:Error){}
}
return object;
}
}
}
Which would then turn the first set of code into a nice one liner like so.
var spr:Sprite = Factory.create(Sprite, {x:20, y:100, alpha:0.5, rotation:15});
July 7th, 2010 at 3:35 pm
I totally agree