遇到多个构造器参数可用考虑builder模式
Posted 点墨小僧
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了遇到多个构造器参数可用考虑builder模式相关的知识,希望对你有一定的参考价值。
public class NutritionFacts {
private final int serviceSize;
private final int servings;
private final int calories;
private final int fat;
public static class Builder {
private final int serviceSize;
private final int servings;
private int calories = 0;
private int fat = 0;
public Builder(int serviceSize, int servings) {
this.serviceSize = serviceSize;
this.servings = servings;
}
public Builder calories(int val) {
calories = val;
return this;
}
public Builder fat(int val) {
fat = val;
return this;
}
public NutritionFacts build() {
return new NutritionFacts(this);
}
}
public NutritionFacts(Builder build) {
// TODO Auto-generated constructor stub
this.serviceSize = build.serviceSize;
this.servings = build.servings;
this.calories = build.calories;
this.fat = build.fat;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
NutritionFacts nutr = new NutritionFacts.Builder(0,0)
.fat(0)
.calories(0)
.build();
}
}
简而言之,如果类的构造器或者静态工厂中有很多参数,设计这种类时,Builder模式是很不错的选择,特别是当大多数参数都是可选的时候。与使用传统的重叠构造器模式相比,用Builder模式的客户端代码将更已于阅读和编写,构建器也比JavaBean更加安全。
以上是关于遇到多个构造器参数可用考虑builder模式的主要内容,如果未能解决你的问题,请参考以下文章
读书笔记 - Effective Java02. 遇到多个构造器参数时要考虑用构建器