Builder模式
Posted tabctrlshift
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Builder模式相关的知识,希望对你有一定的参考价值。
构造方法参数过多时,Builder模式比使用伸缩构造方法(telescoping constructors)更容易读写,比JavaBeans模式更安全。
Builder通常是它所构建的类的一个静态成员类(条目24)。以下是它在实践中的示例:
// Builder Pattern 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 { // Required parameters private final int servingSize; private final int servings; // Optional parameters - initialized to default values private int calories = 0; private int fat = 0; private int sodium = 0; private int carbohydrate = 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 carbohydrate(int val) { carbohydrate = 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; } }
NutritionFacts
类是不可变的,所有的参数默认值都在一个地方。builder的setter方法返回builder本身,这样调用就可以被链接起来,从而生成一个流畅的API。下面是客户端代码的示例:
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8) .calories(100).sodium(35).carbohydrate(27).build();
以上是关于Builder模式的主要内容,如果未能解决你的问题,请参考以下文章
Builder设计模式,模板设计模式,Adapter设计模式笔记