Java最佳實踐(1)-創(chuàng)建對象
使用靜態(tài)工廠方法創(chuàng)建
-
from: 類型轉(zhuǎn)換方法,它只有單個參數(shù),返回該類型的一個相對應(yīng)的實例
Date d = Date.from(instant) -
of:聚合方法,帶有多個參數(shù),返回該類型的一個實例,把他們合并起來
Set<Rank> faceCards=EnumSet.of(JACK, QUEEN, KING) -
valueOf:比from和of更繁瑣的一種替代方法
BigInteger prime=BigInteger.valueOf(Integer.MAX_VALUE) -
instance/getInstance:返回的實例是通過方法的參數(shù)來描述的,但是不能說與參數(shù)具有同樣的值
StackWalk luke=StackWalker.getInstance(options) -
create/newInstance:像instance/getInstance一樣,但create/newInstance能夠確保每次調(diào)用都返回一個新的實例
Object newArray=Array.newInstance(classObject, arrayLen) -
getType:像getInstance一樣,但是工廠方法處于不同的類中的時候使用。Type表示工廠方法所返回的對象類型
FileStore fs=Files.getFileStore(path) -
newType:像newInstance一樣,但是在工廠方法處于不同的類中的時候使用。Type表示工廠方法所返回的對象類型
BufferedReader br=Files.newBufferedReader(path) -
type:getType和newType的簡版
List<Complain> litany=Conllections.list(legacyLitany)
使用建造者(Builder)模式
public class User {
private String username;
private String password;
private String phone;
private String country;
private String city;
}
有一個如下的User類,所有屬性都是String。
如果用構(gòu)造器方法
public User(String username, String password, String phone, String country, String city)
因為全是String,調(diào)用方很有可能會傳值錯誤,比如username傳了password,password傳了username,編譯能通過,IDE也不會報錯,但是運行時結(jié)果卻是錯的。
如果用set方法
User user=new User();
user.setUsername(username);
user.setUsername(password);
user.setUsername(phone);
user.setUsername(country);
user.setUsername(city);
需要寫一大堆set,可以避免錯誤,但是調(diào)用方寫法不夠優(yōu)雅。
下面使用建造者模式進行創(chuàng)建對象:
public class User {
private String username;
private String password;
private String phone;
private String country;
private String city;
public static class Builder {
private String username;
private String password;
private String phone = "";
private String country = "";
private String city = "";
public Builder(String username, String password) {
this.username = username;
this.password = password;
}
public Builder phone(String phone) {
this.phone = phone;
return this;
}
public Builder country(String country) {
this.country = country;
return this;
}
public Builder city(String city) {
this.city = city;
return this;
}
public User build() {
return new User(this);
}
}
private User(Builder builder) {
this.username = builder.username;
this.password = builder.password;
this.phone = builder.phone;
this.country = builder.country;
this.city = builder.city;
}
}
調(diào)用方寫法:
User user=new User.Builder(username,password)
.phone(phone)
.country(county)
.city(city)
.build();
鏈式調(diào)用寫法更簡潔更易讀。
使用try-with-resources的寫法
諸如InputString, BufferedReader之類實現(xiàn)了Closeable接口的類可以使用如下方式創(chuàng)建
try(InputStream in = new ByteArrayInputStream(str.getBytes())){
/**
* 實現(xiàn)了Closeable對象的可以用try-with-resources的寫法,
* 將InputStream之類的寫在try()中不需要再在finally中關(guān)閉
*/
}catch (Exception e){
e.printStackTrace();
}
不需要再寫finally去關(guān)閉,顯得更簡潔易懂