好處:
能保證重疊構造器模式的安全性;
能保證JAVABeans模式的可讀性;
package cn.lonecloud.builder; /** * 使用內部類構建器來對這個類進行構造 * @Title: MyConstractor.java * @Package cn.lonecloud.builder * @Description: * @author lonecloud * @webSite http://wwww.lonecloud.cn * @date 2016年9月12日 上午10:17:11 */ public class MyConstractor { //some field of class private final int size; private final int servings; private final int fat; private final int sodium; private final int age; //using getMethod public int getSize() { return size; } public int getServings() { return servings; } public int getFat() { return fat; } public int getSodium() { return sodium; } public int getAge() { return age; } @Override public String toString() { return "MyConstractor [size=" + size + ", servings=" + servings + ", fat=" + fat + ", sodium=" + sodium + ", age=" + age + "]"; } //using constractMethod init field private MyConstractor(Builder builder){ this.size=builder.size; this.servings=builder.servings; this.fat=builder.fat; this.sodium=builder.sodium; this.age=builder.age; } //using static class to set this class public static class Builder{ //some field of staticClass private final int size; private final int servings; //using method to set field private int fat=0; private int sodium=0; private int age=0; //using constractorMethod to init this final field public Builder(int size, int servings) { this.size = size; this.servings = servings; } //write method to set field; public Builder fat(int fat){ this.fat=fat; return this; } public Builder sodium(int sodium){ this.sodium=sodium; return this; } public Builder age(int age){ this.age=age; return this; } //return MyConstractor public MyConstractor build(){ return new MyConstractor(this); } } }
測試類:
package cn.lonecloud.constactor; import org.junit.Test; import cn.lonecloud.builder.MyConstractor; public class MyTest { @Test public void constractorTest(){ MyConstractor myConstractor = new MyConstractor.Builder(1,2).age(100).build(); System.out.println(myConstractor.toString()); } }