【发布时间】:2014-05-08 06:34:17
【问题描述】:
假设如下情况:
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();
}
}
}
是否有可能通过一些架构巫术来避免 ImplB.b1() 中的 instanceof 检查? ImplA 和 ImplB 在同一个包中,并且彼此密切相关。我在某处读到,instanceof 的使用暗示了“不太好”的界面设计。有什么建议吗?非常感谢!
【问题讨论】:
-
没有更多上下文很难说。
-
您需要什么样的附加信息?
-
Avoiding instanceof in Java 的可能重复项
-
@Raedwald 我读过这篇文章,但我无法将所描述的问题映射到我的案例中。
-
为避免因重复而被关闭,您需要在问题中解释为什么您的问题实际上不是类似问题的重复。您接受了推荐访问者设计模式的答案。这也是Avoiding instanceof in Java 问题的高票答案之一。
标签: java interface casting instanceof