Effective Java 02 Consider a builder when faced with many constructor parameters
Advantage
- It simulates named optional parameters which is easily used to client API.
- Detect the invariant failure(validation error of field) as soon as the invalid parameters are passed, instead of waiting for build to be invoked.
- The builder can fill in some fields automatically such as a serial number.
- Avoid Class.newInstancebreaks compile-time exception checking
Disadvantage
- A builder must be created first. It's time cost and verbose. It would be better to be used when there are more than 4 parameters.
Demo
package com.effectivejava.creatingobject;
// 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 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;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
// TODO Auto-generated method stub
return String
.format("NutritionFacts[servingSize:%d, servings:%d, calories: %d, fat: %d, sodium: %d, carbohydrate: %d]",
this.servingSize, this.servings, this.calories,
this.fat, this.sodium, this.carbohydrate);
}
}
NutritionFacts nutritionFacts = new NutritionFacts.Builder(10, 100)
.calories(3).carbohydrate(2).fat(1).sodium(4).build();
System.out.println(nutritionFacts.toString());
/*******************************************/
// A builder for objects of type T
public interface Builder<T> {
public T build();
}
Tree buildTree(Builder<? extends Node> nodeBuilder) { ... }
Summary
The Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful(>4) of parameters.
Effective Java 02 Consider a builder when faced with many constructor parameters的更多相关文章
- Effective Java Item2:Consider a builder when faced with many constructor parameters
Item2:Consider a builder when faced with many constructor parameters 当构造方法有多个参数时,可以考虑使用builder方式进行处理 ...
- Effective Java 03 Enforce the singleton property with a private constructor or an enum type
Principle When implement the singleton pattern please decorate the INSTANCE field with "static ...
- Effective Java Item3:Enforce the singleton property with a private constructor or an enum type
Item3:Enforce the singleton property with a private constructor or an enum type 采用枚举类型(ENUM)实现单例模式. ...
- Effective Java Index
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...
- Effective Java 目录
<Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...
- 【Effective Java】阅读
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...
- Effective Java —— 多字段下考虑使用建造者模式构建实例
本文参考 本篇文章参考自<Effective Java>第三版第二条"Consider a builder when faced with many constructor pa ...
- 《Effective Java》读书笔记 - 2.创建和销毁对象
Chapter 2 Creating and Destroying Objects item 1:Consider static factory methods instead of construc ...
- Java之进阶(1) -《Effective Java》
第1章 引言 第2章 创建和销毁对象 第1条:考虑用静态工厂方法代替构造器(Consider static factory methods instead of constructors) 第2条:遇 ...
随机推荐
- 【第二课】深入理解Handler
简要讲解Handler是做什么的 我们知道,在Android中,app启动会启动一个进程一个线程——UI线程,UI线程是主线程,并且不允许这个线程阻塞超过5秒,一旦超过5秒就会ANR. 所以较为耗时的 ...
- java switch语句注意的事项
1.switch语句使用的变量只能是byte.char.short.string数据类型. 2.case后面gender数据必须是一个常量. 3.switch的停止条件: switch语句一旦比配上了 ...
- Sprint Three 回顾与总结&发表评论&团队贡献分
● 一.回顾与总结 (1)回顾 燃尽图: Sprint计划-流程图: milestones完成情况如下: (2)总结 从sprint one到three,我们团队配合十分默契,互相帮助,虽然遇到了不少 ...
- Scrum 项目 7.0
------------------7.0------------------------------ Sprint回顾 1.回顾组织 主题:“我们怎样才能在下个sprint中做的更好?” 时间:设定 ...
- AC自动机 - 多模式串的匹配运用 --- HDU 3065
病毒侵袭持续中 Problem's Link:http://acm.hdu.edu.cn/showproblem.php?pid=3065 Mean: 略 analyse: AC自动机的运用. 这一题 ...
- .Net配置文件——反射+配置文件存储类型实例
配置文件+反射确实去除了选择语句的繁琐,带来了优美的赶脚! 首先改进了一下类(接上文): ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ...
- Gridview的RowDataBound事件(添加删除提示,改变背景颜色)
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e) { //如果是绑定数据行 if (e.Row.Row ...
- jQquery.validate自定义规则的使用案例
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 【C++】第1章 在VS2015中用C++编写控制台应用程序
分类:C++.VS2015 创建日期:2016-06-12 一.简介 看到不少人至今还在用VC 6.0开发工具学习C++,其实VC 6.0开发工具早就被淘汰了.这里仅介绍学习C++时推荐使用的两种开发 ...
- SQL Server密码管理的六个危险判断
当管理SQL Server内在的帐户和密码时,我们很容易认为这一切都相当的安全.但实际上并非如此.在这里,我们列出了一些对于SQL Server密码来说非常危险的判断. 当管理SQL Server内在 ...