Effective Java Second Edition --- Builder Pattern
Posted 海阔天空990
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Effective Java Second Edition --- Builder Pattern相关的知识,希望对你有一定的参考价值。
如果类的构造器或者静态工厂中有多个参数,设计这种类时,Builder模式是一种不错的选择,特别是当大多数参数是可选的时候。
与使用传统的重载构造函数模式相比,使用Builder模式的客户端代码更易于阅读和编写,构造器也比javabeens更加安全。
代码如下:
1 /** 2 * Created by zhanga.fnst on 2016/3/14. 3 */ 4 public class NutritionFacts { 5 private final int servingSize; 6 private final int servings; 7 private final int calories; 8 private final int flat; 9 private final int sodium; 10 private final int carbohydrate; 11 12 public static class Builder{ 13 //required parameters 14 private final int servingSize; 15 private final int servings; 16 17 //Optional parameters 18 private int calories = 0; 19 private int flat = 0; 20 private int sodium = 0; 21 private int carbohydrate = 0; 22 23 public Builder(int servingSize,int servings){ 24 this.servingSize = servingSize; 25 this.servings = servings; 26 } 27 28 public Builder calories(int val){ 29 calories = val; 30 return this; 31 } 32 33 public Builder flat(int val){ 34 flat = val; 35 return this; 36 } 37 38 public Builder carbohydrate(int val){ 39 carbohydrate = val; 40 return this; 41 } 42 43 public Builder sodium(int val){ 44 sodium = val; 45 return this; 46 } 47 48 public NutritionFacts build(){ 49 return new NutritionFacts(this); 50 } 51 } 52 53 private NutritionFacts(Builder builder){ 54 servingSize = builder.servingSize; 55 servings = builder.servings; 56 calories = builder.calories; 57 flat = builder.flat; 58 sodium = builder.sodium; 59 carbohydrate = builder.carbohydrate; 60 } 61 }
main方法:
1 /** 2 * Created by zhanga.fnst on 2016/3/14. 3 */ 4 public class TestMain { 5 NutritionFacts cocaCola = new NutritionFacts.Builder(240,8). 6 calories(100).sodium(35).carbohydrate(27).build(); 7 }
以上是关于Effective Java Second Edition --- Builder Pattern的主要内容,如果未能解决你的问题,请参考以下文章