Funny Parameterized Factory

Actionscript:
  1. package{
  2.  
  3.     import flash.utils.getDefinitionByName;
  4.    
  5.     public class Creator{
  6.        
  7.         public function Creator():void{
  8.             // classes we can create
  9.              ClassA;
  10.              ClassB;
  11.         }
  12.  
  13.         public function create(type:String):ISomeInterface{
  14.              var ClassRef:Class = getDefinitionByName(type) as Class;
  15.              return ISomeInterface(new ClassRef());
  16.         }
  17.     }
  18. }

Actionscript:
  1. package{
  2.     public interface ISomeInterface{
  3.         function sayHi():void;
  4.     }
  5. }

Actionscript:
  1. package{
  2.    
  3.     public class ClassA implements ISomeInterface{
  4.        
  5.         public function ClassA(){
  6.             trace("new ClassA()");
  7.         }
  8.        
  9.         public function sayHi():void{
  10.             trace("hello I am a ClassA instance");
  11.         }
  12.     }
  13.      
  14. }

Actionscript:
  1. package{
  2.    
  3.     public class ClassB implements ISomeInterface{
  4.        
  5.         public function ClassB(){
  6.             trace("new ClassB()");
  7.         }
  8.        
  9.         public function sayHi():void{
  10.             trace("hello I am a ClassB instance");
  11.         }
  12.     }
  13.      
  14. }

... and lastly on the timeline:

Actionscript:
  1. var creator:Creator = new Creator();
  2.  
  3. var a:ISomeInterface = creator.create("ClassA");
  4. a.sayHi();
  5.  
  6. var b:ISomeInterface = creator.create("ClassB");
  7. b.sayHi();
  8.  
  9. /*outputs
  10.  
  11. new ClassA()
  12. hello I am a ClassA instance
  13. new ClassB()
  14. hello I am a ClassB instance
  15.  
  16. */

Unfortunately this has some downsides compared to a switch or if statement parameterized factory. Still fun though...

This entry was posted in Uncategorized and tagged , , . Bookmark the permalink. Both comments and trackbacks are currently closed.