代码之家  ›  专栏  ›  技术社区  ›  Dan TheCodeJunkie

让春季国际奥委会与MVP模式合作

  •  1
  • Dan TheCodeJunkie  · 技术社区  · 15 年前

    我正在尝试使用 MVP 与Spring IOC一起使用Swing应用程序设计模式。在MVP中,视图需要自己传递给演示者,我无法解决如何使用Spring实现这一点。

    public class MainView  implements IMainView {
    
        private MainPresenter _presenter;
    
        public MainView() {
    
            _presenter = new MainPresenter(this,new MyService());
    
           //I want something more like this
           // _presenter = BeanFactory.GetBean(MainPresenter.class);
    
        }
    
    }
    

    这是我的配置XML(不正确)

    <bean id="MainView" class="Foo.MainView"/>
    <bean id="MyService" class="Foo.MyService"/>
    
    <bean id="MainPresenter" class="Foo.MainPresenter">
        <!--I want something like this, but this is creating a new instance of View, which is no good-->
       <constructor-arg type="IMainView">
            <ref bean="MainView"/>
        </constructor-arg>
        <constructor-arg  type="Foo.IMyService">
            <ref bean="MyService"/>
         </constructor-arg>
    </bean>
    

    如何将视图导入演示者?

    1 回复  |  直到 12 年前
        1
  •  2
  •   axtavt    15 年前

    可以重写用于创建bean的构造函数参数 BeanFactory.getBean(String name, Object... args) .这种方法的缺点是,查找必须由bean名称而不是其类完成,并且此方法一次重写所有构造函数参数,因此必须使用setter依赖项 MyService :

     public class MainView  implements IMainView { 
    
        private MainPresenter _presenter; 
    
        public MainView() { 
            _presenter = beanFactory.getBean("MainPresenter", this); 
        }  
    }
    

    还注意到 prototype 范围,因为每个 MainView 需要自己 MainPresenter

    <bean id="MyService" class="Foo.MyService"/>   
    
    <bean id="MainPresenter" class="Foo.MainPresenter" scope = "prototype">   
        <constructor-arg type="IMainView"><null /></constructor-arg>   
        <property name = "myService">   
            <ref bean="MyService"/>   
        </property>   
    </bean>