1 public class NutritionFacts { 2 3 private final int servingSize; 4 private final int servings; 5 private final int calories; 6 private final int fat; 7 private final int sodium; 8 private final int carbohydrate; 9 10 // 构造器,静态内部类 11 public static class Builder { 12 // 必要参数 13 private final int servingSize; 14 private final int servings; 15 // 可选参数 16 private int calories = 0; 17 private int fat = 0; 18 private int carbohydrate = 0; 19 private int sodium = 0; 20 21 public Builder(int servingSize, int servings) { 22 this.servingSize = servingSize; 23 this.servings = servings; 24 } 25 26 public Builder calories(int val) { 27 calories = val; 28 return this;//返回Builder类对象本身,以便把调用链接起来 29 } 30 31 public Builder fat(int val) { 32 fat = val; 33 return this; 34 } 35 36 public Builder carbohydrate(int val) { 37 carbohydrate = val; 38 return this; 39 } 40 41 public Builder sodium(int val) { 42 sodium = val; 43 return this; 44 } 45 46 public NutritionFacts build() { 47 return new NutritionFacts(this); 48 } 49 } 50 51 private NutritionFacts(Builder builder) { 52 servingSize = builder.servingSize; 53 servings = builder.servings; 54 calories = builder.calories; 55 fat = builder.fat; 56 sodium = builder.sodium; 57 carbohydrate = builder.carbohydrate; 58 } 59 60 @Override 61 public String toString() { 62 return "[" + 63 "servingSize:" + servingSize + 64 ",servings:" + servings + 65 ",calories:" + calories + 66 ",fat:" + fat + 67 ",sodium:" + sodium + 68 ",carbohydrate:" + carbohydrate + 69 "]"; 70 } 71 72 public static void main(String[] args) { 73 NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8) 74 .calories(100).sodium(35).carbohydrate(27).build(); 75 76 System.out.println(cocaCola); 77 } 78 }
构造Map
1 package com.jt.mongo.demo.basic.util; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 /** 7 * 构建拥有多个值的Map(简化map操作):<br/> 8 * map = ParamBuilder.of().withParam().withParam().withParam().build();. 9 * 10 * @author weihainan. 11 * @since 0.1 created on 2017/2/8. 12 */ 13 public final class ParamBuilder { 14 15 private Map<String, Object> paramMap = new HashMap<>(6); 16 17 private ParamBuilder() { 18 // empty 19 } 20 21 /** 22 * 获取ParamBuilder对象. 23 */ 24 public static ParamBuilder of(){ 25 return new ParamBuilder(); 26 } 27 28 /** 29 * 获取ParamBuilder对象并设置一对key-value. 30 */ 31 public static ParamBuilder of(String paramName, Object paramValue) { 32 return new ParamBuilder().withParam(paramName, paramValue); 33 } 34 35 /** 36 * 设置参数,可多次操作. 37 */ 38 public ParamBuilder withParam(String paramName, Object paramValue) { 39 paramMap.put(paramName, paramValue); 40 return this; 41 } 42 43 /** 44 * 获取最终的map. 45 */ 46 public Map<String, Object> build() { 47 return paramMap; 48 } 49 }