package com.wjy.effective; public class BuilderConstr { private final int age; private final int num; private final int size; public int getAge() { return age; } public int getNum() { return num; } public int getSize() { return size; } public static class Builder{ private final int age; private final int num; private int size=0; public Builder(int age,int num){ this.age=age; this.num=num; } public Builder size(int size){ this.size=size; return this; } public BuilderConstr build(){ return new BuilderConstr(this); } } public BuilderConstr(Builder builder){ age=builder.age; num=builder.num; size=builder.size; } }
客户端代码:
package com.wjy.effective; import com.wjy.effective.BuilderConstr.Builder; /** * @author wjy * */ public class TestBuildConstr { public static void main(String args[]){ BuilderConstr builderConstr=new BuilderConstr.Builder(23, 1).size(88).build(); //以上代码等价于以下三行代码代码: // Builder builder=new BuilderConstr.Builder(23, 1); // builder=builder.size(88); // BuilderConstr builderConstr=builder.build(); System.out.println("age: "+builderConstr.getAge()); System.out.println("num: "+builderConstr.getNum()); System.out.println("size: "+builderConstr.getSize()); } }
运行结果:
age: 23 num: 1 size: 88