开发者

Constructor injection

I know the code is missing (Someone will give negative numbers). But I only want to know how do you solve constructor injection in this situation?

class PresenterFactory
{
public:
  template<class TModel>
    AbstractPresenter<TModel>*
    GetFor(AbstractView<TModel> * view)
    {
      return new PresenterA(view, new FakeNavigator());
    }
};

class ViewA : public AbstractView<ModelA>
{
  static PresenterFactory factory;
public:
  ViewA(AbstractPresenter<ModelA> *presenter = factory.GetFor<Mo开发者_运维技巧delA>(this)) :
    AbstractView<ModelA> (presenter)
  {
  }

  // this one is also not working
  // invalid use of ‘class ViewA’
  //  ViewA()
  //  {
  //    this->ViewA(factory.GetFor<ModelA> (this));
  //  }
};


Why not to use two constructors?

// constructor with one argument
ViewA(AbstractPresenter<ModelA> *presenter) : AbstractView<ModelA> (presenter)
{
}

// constructor without arguments
ViewA() : AbstractView<ModelA>(factory.GetFor<ModelA>(this))
{
}

By the way, this pointer is valid only within nonstatic member functions. It should not be used in the initializer list for a base class. The base-class constructors and class member constructors are called before this constructor. In effect, you've passed a pointer to an unconstructed object to another constructor. If those other constructors access any members or call member functions on this, the result will be undefined. You should not use the this pointer until all construction has completed.


public class ConstEx {

    String name;
    Integer id;
    public ConstEx(String name, Integer id) {

        System.out.println("--------Constructor Firs -------");
    }

    public ConstEx(Integer id,String name) 
    {
        System.out.println("-----Second Constructor--------");
    }
}




with th Following Configuration in xml

<bean id="const1" class="com.spring.hari.springexample.ConstEx">
        <constructor-arg type="java.lang.Integer" >
            <value>10</value>
        </constructor-arg>
        <constructor-arg type="java.lang.String" >
            <value>100</value>
        </constructor-arg>
    </bean>


Why First Constructor is called since i have mentioned the types even than it is calling first constructor
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜