• java_可变参数构造器 Bulder模式


    package com.test1.www;
    
    class NutritionFacts {
    	//必须
    	private int servingSize;
    	private int servings;
    	//可选, Build类必须初始化
    	private int calories;
    	private int fat;
    	private int sodium;
    	private int carboohydrate;
    	
    	public int getServingSize() {
    		return servingSize;
    	}
    
    
    	public int getServings() {
    		return servings;
    	}
    
    
    	public int getCalories() {
    		return calories;
    	}
    
    
    	public int getFat() {
    		return fat;
    	}
    
    
    	public int getSodium() {
    		return sodium;
    	}
    
    
    	public int getCarboohydrate() {
    		return carboohydrate;
    	}
    
    
    	static class Builder {
    		private int servingSize;
    		private int servings;
    		private int calories=0;
    		private int fat=0;
    		private int sodium=0;
    		private int carboohydrate=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 sodium(int val) {
    			sodium = val;
    			return this;
    		}
    
    		public Builder carboohydrate(int val) {
    			carboohydrate = val;
    			return this;
    		}
    		public NutritionFacts build() {
    			return new NutritionFacts(this);
    		}
    
    	}
    
    	
    	public NutritionFacts(Builder builder){
    		servingSize = builder.servingSize;
    		 calories=builder.calories;
    		 fat=builder.fat;
    		 sodium = builder.sodium;;
    		 carboohydrate= builder.carboohydrate;
    		
    	}
    }
    
    public class Demo2 {
    	public static void main(String[] args) {
    		NutritionFacts nt = new NutritionFacts.Builder(240, 8).calories(20).carboohydrate(30).fat(20).sodium(2).build();
    		
    		System.out.println(nt.getServingSize());
    		System.out.println(nt.getServings());
    		System.out.println(nt.getCalories());
    		System.out.println(nt.getFat());
    		System.out.println(nt.getCarboohydrate());
    		System.out.println(nt.getSodium());
    	}
    }
    


  • 相关阅读:
    数据库的创建与管理
    html+css画虚线,实线
    隐藏导航练习
    表单—注册邮箱
    整理—运算符l
    softmax函数理解
    离线配置Anaconda3+tensorflow-gpu1.4.0+cuda8.0+cudnn6.0
    stl总结精简版
    hdu_2030
    康托展开
  • 原文地址:https://www.cnblogs.com/MarchThree/p/3720427.html
Copyright © 2020-2023  润新知