读书人

小弟我的 effective java - 构建器

发布时间: 2012-08-28 12:37:01 作者: rapoo

我的 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();}}

读书人网 >编程

热点推荐