考虑使用静态代码块
/** * 静态代码块 * * @author iHelin * @since 2017/11/27 14:21 */public class BabyBoomer { private static Date birthDate; private static final Date BOOM_START; private static final Date BOOM_END; static { Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0); BOOM_START = gmtCal.getTime(); gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0); BOOM_END = gmtCal.getTime(); } public static boolean isBabyBoomer() { return birthDate.compareTo(BOOM_START) >= 0 && birthDate.compareTo(BOOM_END) < 0; } public static void main(String[] args) { Calendar cal = Calendar.getInstance(); cal.set(1947, Calendar.FEBRUARY, 1, 0, 0, 0); birthDate = cal.getTime(); System.out.println(isBabyBoomer()); }}复制代码
BOOM_START
和BOOM_END
不变,考虑使用静态常量,然后使用静态代码块初始化。
使用枚举实现单例
/** * 单例 - 使用枚举实现 * * @author iHelin * @since 2017/11/27 14:27 */public class Elvis { private static final Elvis INSTANCE = new Elvis(); private Elvis() { } public static Elvis getInstance() { return INSTANCE; } public Object readResolve() { return INSTANCE; }}复制代码
遇到多个构造器参数时考虑用构建器
/** * 遇到多个构造器参数时考虑用构建器 * * @author iHelin * @since 2017/11/27 14:24 */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 { /** * Required parameters */ private final int servingSize; private final int servings; /** * Optional parameters */ private int calories = 0; private int fat = 0; private int sodium = 0; private int carbohydrate = 0; 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() { 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; } public static void main(String[] args) { NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build(); System.out.println(cocaCola); } @Override public String toString() { return ToStringBuilder.reflectionToString(this); }}复制代码