目前在开发程序时要实例化某一接口,而不知道接口是哪一个类实现,如果用Robotlegs来做是很好的。
我尝试用
injector.instantiate(IRobot);
但是程序始终报错,后来才发现接口是不能直接用instantiate方法来做。如果要用Injector来做,可以采用如下方法:
injector.getMapping(IRobot).getResponse() as IRobot;
平时一般向类中注入接口代码如下:
AS CODE:
- public class Robot implements IRobot {
- private var _leftLeg : ILeg;
- private var _rightLeg : ILeg;
- public function get leftLeg() : ILeg {
- return _leftLeg;
- }
- [Inject(name="leftLeg")]
- public function set leftLeg(leg : ILeg) : void {
- _leftLeg = leg;
- }
- public function get rightLeg() : ILeg {
- return _rightLeg;
- }
- [Inject(name="rightLeg")]
- public function set rightLeg(leg : ILeg) : void {
- _rightLeg = leg;
- }
- }
上面代码中ILeg就是在Robot类实例化时注入,将会由Injector类自动调用injector.getMapping(ILeg).getResponse() as ILeg;
另外还有一个收获,如下代码,先映射Robot,IRobot为单例:
AS CODE:
- private function init(e:Event):void{
- injector = new Injector();
- injector.mapSingleton(Robot);
- injector.mapSingletonOf(IRobot, Robot);
- //injector.mapClass(IRobot, Robot);
- injector.mapClass(ILeg, Leg,"leftLeg");
- injector.mapClass(ILeg, Leg,"rightLeg");
- injector.mapValue(String, "my robot no.1","robotName");
- //injector.mapValue(IRobot, injector.instantiate(Robot));
- }
再看如下代码:
AS CODE:
- var robot:IRobot = injector.getMapping(IRobot).getResponse() as IRobot;
- var robotClone:Robot = injector.instantiate(Robot);
这时的变量robot与robotClone是否为同一Robot对象实例的引用呢?
测试结果告诉我是相等的。
Tags: Flex, ioc, robotlegs
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.