gpt4 book ai didi

java - Joshua Bloch 对 Builder 模式的一些修改

转载 作者:搜寻专家 更新时间:2023-10-31 19:36:00 26 4
gpt4 key购买 nike

我使用 Joshua Bloch 介绍的 Java 构建器模式。有时,我发现与原始类型相比,使用默认值初始化某些字段的开销更高。

因此,我的策略是什么。

  1. 我延迟了这些字段的默认值初始化操作。
  2. 在构建过程中,如果调用者之前没有设置它们,我只会将它们初始化为默认值。

我不确定这样做是否?有没有可能发生?比如,线程安全问题?到目前为止,我没有发现任何问题。

package sandbox;

import java.util.Calendar;

/**
*
* @author yccheok
*/
// Builder Pattern
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;

private final java.util.Calendar calendar; // !!!

public static class Builder {
// Required parameters
private final int servingSize;
private final int servings;
// Optional parameters - initialized to default values
private int calories = 0;
private int fat = 0;
private int carbohydrate = 0;
private int sodium = 0;

// We suppose to provide a default value for calendar. However, it may
// seem expensive. We will do it later during build.
private java.util.Calendar calendar = null;

public Builder(int servingSize, int servings) {
this.servingSize = servingSize;
this.servings = servings;
}
public Builder calories(int val)
{ calories = val; return this; }
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() {
// !!!
if (this.calendar == null) {
this.calendar = Calendar.getInstance();
}
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;
calendar = builder.calendar;
}
}

最佳答案

如果我真的希望日历为空怎么办?那么你的模式将不起作用。否则,对我来说似乎没问题。

关于java - Joshua Bloch 对 Builder 模式的一些修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3718562/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com