构造器模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | package org.effectivejava.examples.chapter02.item02.builder; 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 - initialized to default values 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 ; } 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(); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步