Skip to content


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对象实例的引用呢?

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

Tags: Flex, ioc, robotlegs

相关文章

Posted in FLEX专题.

Tagged with , , .


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

You must be logged in to post a comment.