vendredi 22 novembre 2019

Java design pattern for use different implementation of method with an abstract class as param

I got a problem of conception in my programm.

I got 4 classes (ChildA, ChildB, ChildC) who extends a parent class (Parent)

i got a method like it :

public void doInteraction(Parent a, Parent b){
a.doActionWith(b);
b.doActionWith(a);
}

My 3 child class and parent class :

public abstract class Parent {
    public abstract void doActionWith(Parent other);
}

class ChildA extends Parent {

    @Override
    public void doActionWith(Parent other) {
        System.out.println("childA use doActionWith abstract");
    }

    public void doActionWith(ChildA chila) {
        System.out.println("childA use doActionWith childA");
    }

    public void doActionWith(ChildB chilb) {
        System.out.println("childA use doActionWith childB");
    }

    public void doActionWith(ChildC chilb) {
        System.out.println("childA use doActionWith childC");
    }

}

class ChildB extends Parent {

    @Override
    public void doActionWith(Parent other) {
        System.out.println("childB use doActionWith abstract");
    }

    public void doActionWith(ChildA childa) {
        System.out.println("childB use doActionWith childA");
    }

    public void doActionWith(ChildB chilb) {
        System.out.println("childB use doActionWith childB");
    }

    public void doActionWith(ChildC chilb) {
        System.out.println("childB use doActionWith childC");
    }

}

class ChildC extends Parent {

    @Override
    public void doActionWith(Parent other) {
        System.out.println("childB use doActionWith abstract");
    }

    public void doActionWith(ChildA childa) {
        System.out.println("childB use doActionWith childA");
    }

    public void doActionWith(ChildB chilb) {
        System.out.println("childB use doActionWith childB");
    }

    public void doActionWith(ChildC chilc) {
        System.out.println("childC use doActionWith childC");
    }

}

When i call a.doActionWith(b); in doInteraction method : the abstract method is always used event the jvm knows the real type of a and b.

Why java dont use specific method with argument match exactly the type of param ?

The only solution i find , is to cast object to their child type. But i need to check their type with instance of.(imagine if i got 20 child class). And i remember my studies that an instance of reveals a bad conception.

I try some stuff like

    public abstract <C extends Parent> void doActionWith(C other);

but same. I imagine a design pattern solve this problem but i dont find it. Maybe i should use interface, but i don't see how i should do it.

Thanks for reading.

fabien.

Aucun commentaire:

Enregistrer un commentaire