Actionscript:
-
package{
-
-
import flash.utils.getDefinitionByName;
-
-
public class Creator{
-
-
public function Creator():void{
-
// classes we can create
-
ClassA;
-
ClassB;
-
}
-
-
public function create(type:String):ISomeInterface{
-
var ClassRef:Class = getDefinitionByName(type) as Class;
-
return ISomeInterface(new ClassRef());
-
}
-
}
-
}
Actionscript:
-
package{
-
public interface ISomeInterface{
-
function sayHi():void;
-
}
-
}
Actionscript:
-
package{
-
-
public class ClassA implements ISomeInterface{
-
-
public function ClassA(){
-
trace("new ClassA()");
-
}
-
-
public function sayHi():void{
-
trace("hello I am a ClassA instance");
-
}
-
}
-
-
}
Actionscript:
-
package{
-
-
public class ClassB implements ISomeInterface{
-
-
public function ClassB(){
-
trace("new ClassB()");
-
}
-
-
public function sayHi():void{
-
trace("hello I am a ClassB instance");
-
}
-
}
-
-
}
... and lastly on the timeline:
Actionscript:
-
var creator:Creator = new Creator();
-
-
var a:ISomeInterface = creator.create("ClassA");
-
a.sayHi();
-
-
var b:ISomeInterface = creator.create("ClassB");
-
b.sayHi();
-
-
/*outputs
-
-
new ClassA()
-
hello I am a ClassA instance
-
new ClassB()
-
hello I am a ClassB instance
-
-
*/
Unfortunately this has some downsides compared to a switch or if statement parameterized factory. Still fun though...