zoukankan      html  css  js  c++  java
  • 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());
    	}
    }
    


  • 相关阅读:
    什么是看板方法?
    瓶颈法则
    累积流图——你还没有用过吗?
    为什么我们关注看板方法?
    蒟蒻报道
    博客更换通知
    浅谈树套树(线段树套平衡树)&学习笔记
    浅谈FFT(快速博立叶变换)&学习笔记
    题解 洛谷P1903/BZOJ2120【[国家集训队]数颜色 / 维护队列】
    题解 洛谷P4550/BZOJ1426 【收集邮票】
  • 原文地址:https://www.cnblogs.com/MarchThree/p/3720427.html
Copyright © 2011-2022 走看看