Buileder模式应用

如果类的构造器或者静态工厂具有多个参数,设计这种类时,Builder模式就是种不错的选择,特别是当大多数参数都是可选的时候。它比javabeans更加安全。

 例子代码:

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{ private final int servingSize; private final int servings; 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; } /** * @param args * test */ public static void main(String[] args) { // TODO Auto-generated method stub NutritionFacts cocaCola = new NutritionFacts.Builder(240,8).calories(100).sodium(35).carbohydrate(27).build(); System.out.println(cocaCola.calories); } }

你可能感兴趣的:(String,Class,Build,javabeans)