简体   繁体   中英

Avoid instanceof in Java interface implementation

Assuming the following situation:

public interface A {
    void a1();
    void a2();
}

public interface B {
    void b1(A a);
}

public class ImplA implements A {
    // interface methods
    void a1() {};
    void a2() {};
    // ImplA specific methods
    void a3() {};
}

public class ImplB implements B {
    void b1(A a) {
       if(a instaceof ImplA) { // avoid instanceof test and cast 
          ((ImplA)a).a3(); 
       }
    }
}

Would it be possible by some architectural voodoo to avoid an instanceof check in ImplB.b1()? ImplA and ImplB are in the same package and closely related to each other. I read somewhere, that the use of instanceof is a hint for a "no-so-good" interface design. Any recommendations? Thanks alot!

You could use a Visitor pattern to avoid the instanceof cast

public interface Visitor {
    void visitImplA(ImplA toVisit);
}

public class VisitorImpl implements Visitor {

    @Override
    public void visitImplA(ImplA toVisit) {
        toVisit.a3();
    }
}

public interface A {
    void a1();
    void a2();
    void accept(Visitor visitor);
}

public interface B {
    void b1(A a);
}

public class ImplA implements A {
    // interface methods
    void a1() {};
    void a2() {};
    // ImplA specific methods
    void a3() {};

    void accept(Visitor visitor) {
        visitor.visitImplA(this);
    }
}

public class ImplB implements B {
    void b1(A a) {
        a.accept(new VisitorImpl());
    }
}

This would eliminate all you instanceof checks and divide them into the visitor and the implementing classes, this pattern would suffice in the case where you'd be doing the same stuff after most of the instanceof checks, otherwise you'd need a lot of implementations of the Visitor interface

The VooDoo you want is composition. You can solve that using Visitor dessign pattern. But ther is some penalty when you are using it. Or you can create onther interface that will be used to invoke that a3 method.

The case varry. The reason of question might be that your architecture is not consist and you trying to do something strange or your class perform to many things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM