構造者模式

你是否打過如下代碼:安全

public class Animal{
private String name;
private String breed;
private String gender;
private int weight;

public Animal(String name, String breed) {
this.name = name;
this.breed = breed;
}


public Animal(String name, String breed,String gender,int weight) {
this.name = name;
this.breed = breed;
this.gender=gender;
this.weight=weight;
}

}



上述代碼,致使了在構造過程當中JavaBean可能處於不一致的狀態,也就是說實例化對象本該是一鼓作氣,但如今卻分割成了兩大步,這會致使它線程不安全,進一步引起不可預知的後果。
Effective+Java做者joshua bloch推薦利用"Builder"模式(構造者模式),其核心就是不直接生成想要的對象,而是讓客戶端利用全部必要的參數調用構造器(或者靜態工廠),
獲得一個builder對象,再調用相似setter的方法設置相關可選參數。

代碼以下:

public class Animal{
private String name;
private String breed;
private String gender;
private int weight;


public static class Builder {
private String name;
private String breed;
private String gender;
private int weight;


public Builder(String name, int weight){
this.name=name;
this.weight=weight; }

public Builder gender(String gender){
this.gender=gender;
return this; }

public Builder breed(String breed){
this.breed=breed;
return this; }

public Animal build(){
return new Animal(this); }

}

private Animal(Builder builder){
this.name=builder.name;
this.breed=builder.breed;
this.gender=builder.gender;
this.weight=builder.weight; }

}

 調用:
Animal animal=new Animal.Builder("Tom",10).breed("Cat").build();
相關文章
相關標籤/搜索