我的 effective java -- 構建器

 

 

public class TestConstruct {

private final int serviceSize;

private final int servings;

private final int cal;

private final String fat;

private final boolean istrue;

public static class Builder {

private final int serviceSize;

private final int servings;

private  int cal = 0;

private  String fat = "";

private  boolean istrue = false;

public Builder(int serviceSize, int servings){

this.serviceSize = serviceSize;

this.servings = servings;

}

public Builder calMe(int val){

cal = val;

return this;

}

public Builder fatMe(String val){

fat = val;

return this;

}

public Builder istrueMe(boolean val){

istrue = val;

return this;

}

public TestConstruct build(){

return new TestConstruct(this);

}

}

public TestConstruct(Builder builder){

serviceSize = builder.serviceSize;

servings = builder.servings;

cal = builder.cal;

fat = builder.fat;

istrue = builder.istrue;

}

public void printAll(){

System.out.println(serviceSize);

System.out.println(servings);

System.out.println(cal);

System.out.println(fat);

System.out.println(istrue);

}

}


public class ConstructClient {
public static void main(String[] args) {
TestConstruct tt = new TestConstruct.Builder(1,20).calMe(1).fatMe("123").istrueMe(true).build();
tt.printAll();
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章