從一個輸入點的最好辦法是讓父類中的一個接口,在孩子指定嵌套類。這樣你就不需要將參數投射到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