链式编程:遇到多个构造器参数(Constructor Parameters)时要考虑用构建器(Builder)

时间:2023-12-09 23:30:31

 public class NutritionFacts {

     private final int servingSize;
private final int servings;
private final int calories;
private final int fat;
private final int sodium;
private final int carbohydrate; // 构造器,静态内部类
public static class Builder {
// 必要参数
private final int servingSize;
private final int servings;
// 可选参数
private int calories = 0;
private int fat = 0;
private int carbohydrate = 0;
private int sodium = 0; public Builder(int servingSize, int servings) {
this.servingSize = servingSize;
this.servings = servings;
} public Builder calories(int val) {
calories = val;
return this;//返回Builder类对象本身,以便把调用链接起来
} public Builder fat(int val) {
fat = val;
return this;
} public Builder carbohydrate(int val) {
carbohydrate = val;
return this;
} public Builder sodium(int val) {
sodium = val;
return this;
} public NutritionFacts build() {
return new NutritionFacts(this);
}
} private NutritionFacts(Builder builder) {
servingSize = builder.servingSize;
servings = builder.servings;
calories = builder.calories;
fat = builder.fat;
sodium = builder.sodium;
carbohydrate = builder.carbohydrate;
} @Override
public String toString() {
return "[" +
"servingSize:" + servingSize +
",servings:" + servings +
",calories:" + calories +
",fat:" + fat +
",sodium:" + sodium +
",carbohydrate:" + carbohydrate +
"]";
} public static void main(String[] args) {
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8)
.calories(100).sodium(35).carbohydrate(27).build(); System.out.println(cocaCola);
}
}

构造Map

 package com.jt.mongo.demo.basic.util;

 import java.util.HashMap;
import java.util.Map; /**
* 构建拥有多个值的Map(简化map操作):<br/>
* map = ParamBuilder.of().withParam().withParam().withParam().build();.
*
* @author weihainan.
* @since 0.1 created on 2017/2/8.
*/
public final class ParamBuilder { private Map<String, Object> paramMap = new HashMap<>(6); private ParamBuilder() {
// empty
} /**
* 获取ParamBuilder对象.
*/
public static ParamBuilder of(){
return new ParamBuilder();
} /**
* 获取ParamBuilder对象并设置一对key-value.
*/
public static ParamBuilder of(String paramName, Object paramValue) {
return new ParamBuilder().withParam(paramName, paramValue);
} /**
* 设置参数,可多次操作.
*/
public ParamBuilder withParam(String paramName, Object paramValue) {
paramMap.put(paramName, paramValue);
return this;
} /**
* 获取最终的map.
*/
public Map<String, Object> build() {
return paramMap;
}
}