设计模式--Builder模式
本文地址:http://www.cnblogs.com/masque/p/3817310.html
转载请在明显位置标明出处
1 public class Main5{ 2 3 private final int servingSize; 4 5 private final int servings; 6 7 private final int calories; 8 9 private final int fat; 10 11 private final int sodium; 12 13 private final int carbohydrate; 14 15 public static class Builder{ 16 17 private final int servingSize; 18 19 private final int servings; 20 21 private int calories = 0; 22 23 private int fat = 0; 24 25 private int sodium = 0; 26 27 private int carbohydrate = 0; 28 29 public Builder(int servingSize,int servings){ 30 this.servingSize = servingSize; 31 this.servings = servings; 32 } 33 34 public Builder calories(int calories){ 35 this.calories = calories; 36 return this; 37 } 38 39 public Builder fat(int fat){ 40 this.fat = fat; 41 return this; 42 } 43 44 public Builder sodium(int sodium){ 45 this.sodium = sodium; 46 return this; 47 } 48 49 public Builder carbohydrate(int carbohydrate){ 50 this.carbohydrate = carbohydrate; 51 return this; 52 } 53 54 public Main5 build(){ 55 return new Main5(this); 56 } 57 } 58 59 private Main5(Builder builder){ 60 servingSize = builder.servingSize; 61 servings = builder.servings; 62 calories = builder.calories; 63 fat = builder.fat; 64 sodium = builder.sodium; 65 carbohydrate = builder.carbohydrate; 66 } 67 }
当一个类有很多属性
有很多的熟悉可以是默认的值的时候
可以通过写多个不同参数的构造方法去实现
但是很麻烦
这种方式设计上很灵活
基本上可以上任意的组合见Effective java (中文第二版) 第11页