如果不希望使用new 關(guān)鍵詞創(chuàng)建對象,則可以把構(gòu)造函數(shù)的訪問權(quán)限設(shè)置為private
,尤其是那些只包含靜態(tài)方法的工具類。
class MovieUtils{
private MovieUtils(){}
static String titleAndYear(Movie movie){//代碼內(nèi)容
}
}
使用靜態(tài)工廠方法代替new
關(guān)鍵詞創(chuàng)建對象,工廠方法通過不同的命名可以根據(jù)需要返回不同的子類對象,而且如果需要可以不用每次都創(chuàng)建新對象。
[Update] 一個(gè)讀者提出一個(gè)建議:使用靜態(tài)工廠后不方便測試,如果是這樣,可以在測試期通過使用非靜態(tài)工廠來模擬。class Movie{
//代碼內(nèi)容
static static Movie create(String title){return new Movie(title);
}
}
當(dāng)構(gòu)造方法中有超過三個(gè)參數(shù)時(shí),可以考慮使用builder去構(gòu)建對象,可能有些繁瑣,但是這樣易于擴(kuò)展且可讀性更強(qiáng)。如果是創(chuàng)建一個(gè) value class,可以使用AutoValue
static Builder newBuilder() {
String title;
Builder withTitle(String title) {
this.title = title;
return this;}
private Movie(String title) {
//代碼內(nèi)容
}}
如果創(chuàng)建內(nèi)部類時(shí)不依賴外部類,一定要定義為靜態(tài)類,否則內(nèi)部類的實(shí)例會(huì)持有外部類實(shí)例的引用。
static class MovieAward() {
//代碼內(nèi)容
}}