2013-07-30 56 views
0

我目前正在研究一個面向對象的設計項目,並且想知道是否有更好的方法來驗證子類的增變器中的數據。爲了驗證而覆蓋mutator方法

例如,我有一個家庭類與子類公寓,公寓和房子。在Home類中,我想包含子類共享的(私有)字段的增變器。說其中一個領域是方形的Footage。有沒有辦法讓Home中的mutator足夠通用,以便子類可以爲squareFootage設置自己的有效值,而不必完全重寫mutator?也就是說,我想爲每個子類使用squareFootage的不同有效範圍。

我試着在Home中設置可能的範圍值,然後在子類中覆蓋它們。不幸的是,Home中的mutator仍然是從Home類抓取的,而不是子類。所以,我已經採取了抽象的增變,但不幸的是這導致了很多重複的代碼,因爲我可以從字面上複製和粘貼每個子類中的增變。

我想使可能的範圍值爲靜態的,如果可能的話,我明白這可能與反射,但我真的想避免使用它在這個項目。

+1

你能告訴我們一些關於你想描述的問題的代碼嗎? – Bnrdo

回答

1

我覺得是可以通過添加一個抽象的「驗證」方法必須在子類中實現,這樣的事:

public class Home { 

    private float squareFootage; 

    public abstract void validateSquareFootage() throws MyValidationException; // you could throw an exception, runtime exception or return a boolean to indicate if value is valid or not 

    public void setSquareFootage(float squareFootage) { 
     validateSquareFootage(squareFootage); // again, throws exception or returns boolean, up to you 
     this.squareFootage = squareFootage; 
    } 

    // ... rest of implementation 
} 

而且在subclase:

public class Condo extends Home { 

    @Override 
    public void validateSquareFootage(float squareFootage) throws MyValidationException { 
     // ... do validations 
    } 

} 

,你不必重寫mutator,只需實現正確的驗證器即可。

+0

嗯,看起來像它會工作。這很有趣 - 過去我實際上已經實施了這種方法,但是我太專注於試圖解決缺乏抽象領域的問題。謝謝! – Lathan

0

可能最好將Home類設爲一個抽象類,並在您的子類中進行擴展。通過這種方式,您可以在家庭類中創建適用於所有子類的方法,但可以在子類中覆蓋它們。

0

如果我正確理解您的問題,我認爲您需要這樣的東西?

abstract class Home<T>{ 
    protected T squareFootage; 
    abstract void setSquareFootage(T t); 
} 

class Apartment extends Home<String>{ 
    @Override void setSquareFootage(String t) { 
     //...do something about the parameter 
     this.squareFootage = t; 
    } 
} 

class Condo extends Home<Integer>{ 
    @Override void setSquareFootage(Integer t) { 
     //...do something about the parameter 
     this.squareFootage = t; 
    } 
} 

class House extends Home<Boolean>{ 
    @Override void setSquareFootage(Boolean t) { 
     //...do something about the parameter 
     this.squareFootage = t; 
    } 
}