mardi 2 juin 2020

Dagger2: How to inject a member variable during polymorphism?

public class A {
    B mB;
    public A() {
        createB();
    }
    public void createB() {
        mB = new B();
    }
}

public class ChildA extends A {

    public ChildA() {
        super();
    }
    public void createB() {
        mB = new ChildB();
    }
}

public class B {
    public B() {
    }
}

public class ChildB extends B {
    public ChildB() {
    }
}

public class DemoApp {
    public static void main(String[] args) {
        A a = new ChildA();
    }
}

According to above code, we can see: 1. when a A is newed, a B is created 2. when a ChildA is newed, a ChildB is created.

My question is how can I inject mB in this polymorphism situation? If the design pattern is inappropriate, how can I refractor the code?

Aucun commentaire:

Enregistrer un commentaire