从一个输入点的最好办法是让父类中的一个接口,在孩子指定嵌套类。这样你就不需要将参数投射到func上。这不会降低复杂性,但它确实能让你的意图变得更加清晰,并减少/消除了投射的必要(总是一件好事)。
public abstract class Parent {
interface Interface1 {
//Specifications of methods that all child nested classes must have
}
interface Interface2 {
//Specifications of methods that all child nested classes must have
}
public abstract Interface2 func(Interface1 obj);
}
public class Child extends Parent {
private static class Impl1 implements Interface1 {
//Implementations of methods in Interface1 as they pertain to Child
}
private static class Impl2 implements Interface2 {
//Implementations of methods in Interface2 as they pertain to Child
}
@Override
public Interface2 func(Interface1 obj) {
//Should only have to use methods declared in Interface1
//Thus should have no need to cast obj.
//Will return an instance of Impl2
return null;
}
}
在更广泛的范围内,您应该问自己为什么每个孩子都需要自己的一套嵌套类。如果可以将嵌套类定义移动到父类(并使其成为静态),并且只需在构造过程中根据需要对子类进行定制,则这将变得更简单。
谢谢! 。嵌套类的定义在所有孩子中是不同的。所以我无法将它们作为独立的静态类。你能想出一种方法来改进设计吗? – mc20
鉴于这一点,设计问题是为什么你需要父项中的抽象方法?假设我有'Parent p = ...',我不知道它的类型,我可以用正确的参数调用'p.func(...)'吗?如果不是抽象方法没有意义的话 – Mshnik