Robotlegs IOC 接口实例化

目前在开发程序时要实例化某一接口,而不知道接口是哪一个类实现,如果用Robotlegs来做是很好的。

我尝试用

injector.instantiate(IRobot);

但是程序始终报错,后来才发现接口是不能直接用instantiate方法来做。如果要用Injector来做,可以采用如下方法:

injector.getMapping(IRobot).getResponse() as IRobot;

平时一般向类中注入接口代码如下:

AS CODE:
  1. public class Robot implements IRobot {  
  2.         private var _leftLeg : ILeg;  
  3.         private var _rightLeg : ILeg;  
  4.   
  5.         public function get leftLeg() : ILeg {  
  6.             return _leftLeg;  
  7.         }  
  8.           
  9.         [Inject(name="leftLeg")]  
  10.         public function set leftLeg(leg : ILeg) : void {  
  11.             _leftLeg = leg;  
  12.         }  
  13.           
  14.         public function get rightLeg() : ILeg {  
  15.             return _rightLeg;  
  16.         }  
  17.           
  18.         [Inject(name="rightLeg")]  
  19.         public function set rightLeg(leg : ILeg) : void {  
  20.             _rightLeg = leg;  
  21.         }  
  22.     }  

上面代码中ILeg就是在Robot类实例化时注入,将会由Injector类自动调用injector.getMapping(ILeg).getResponse() as ILeg;

另外还有一个收获,如下代码,先映射Robot,IRobot为单例:

AS CODE:
  1. private function init(e:Event):void{  
  2.                 injector = new Injector();  
  3.                 injector.mapSingleton(Robot);  
  4.                 injector.mapSingletonOf(IRobot, Robot);  
  5.                   
  6.                 //injector.mapClass(IRobot, Robot);  
  7.                 injector.mapClass(ILeg, Leg,"leftLeg");  
  8.                 injector.mapClass(ILeg, Leg,"rightLeg");  
  9.                 injector.mapValue(String, "my robot no.1","robotName");  
  10.                   
  11.                 //injector.mapValue(IRobot, injector.instantiate(Robot));  
  12.             }  

再看如下代码:

AS CODE:
  1. var robot:IRobot = injector.getMapping(IRobot).getResponse() as IRobot;  
  2. var robotClone:Robot = injector.instantiate(Robot);  

这时的变量robot与robotClone是否为同一Robot对象实例的引用呢?

测试结果告诉我是相等的。

下面文章或许你还感兴趣

  • FWD: Creating an Executable Apache Pivot App using Maven
  • 如何获取Flex对象实例的Class
  • FDT3.5正式版已经发布
  • xViewer for flex
  • Robotlegs Framework1.02 & Swiftsuspends1.5 beta2
  • Robotlegs 框架事件的理解
  • 收藏-Flex Builder 3 on Eclipse 3.5
  • Flex 3 Style Explorer
  • Flexmojos Using ASDoc
  • 收藏Flexmojos Adding libraries to compilation

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>