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条:遇 ...
随机推荐
- UNIQUEIDENTIFIER列上的统计信息
UNIQUEIDENTIFIER列上的统计信息非常有意思,在它上面有一些很令人讨厌的行为.我们来看下. 问题重现(The repro) 为了向你展示我们刚抱怨的行为,我用下列简单的表定义创建了一个数据 ...
- xss-跨站脚本攻击-后台传给前端的html标签安全显示
作用 后台拼接的html字符串传到前端,默认是不安全的,需要告诉前端这个字符串是安全的,可以正常显示html标签. 知识点 1.定义 2 3 <script> 获取session ...
- 给你的博客加上“Fork me on Github”彩带
起 如今,随着Git的大热以及Github的优越性,许多知名开源项目都将源代码托管到Github上了.在Github上不仅可以托管自己的开源项目,还可以Fork人家的源代码,给自己感兴趣的项目评价(s ...
- ok6410 android driver(12)
In this essay, I will talk about how to write the service libraries. TIPS : I won't discuss the name ...
- P6 Professional Installation and Configuration Guide (Microsoft SQL Server Database) 16 R1
P6 Professional Installation and Configuration Guide (Microsoft SQL Server Database) 16 R1 May ...
- vs2015 Android SDK
It was not possible to complete an automatic installation. This might be due to a problem with your ...
- 使用openssl生成RSA公私密钥
在windows 环境下 1.进入cmd命令窗口 切换到openssl程序目录下 2.输入openssl.exe,进入openssl命令模式下 3.生成私钥输入“genrsa -out app_pri ...
- C#中得到两个数百分比 (转)
//此方法得到的百分比后小数太多,不行double percent=Convert.ToDouble(2)/Convert.ToDouble(34); string result=(percent*1 ...
- 调试报“The source file is different from when the module was built.”问题的解决
It is related to the checksums which is used to ensure that you are stepping in matching source. You ...
- 转帖一篇sixxpack破解的文章!
星期天闲着没事玩游戏,玩游戏不能无外挂.于是百度了半天,找到了一个,看介绍貌似不错,就下载了下来.一看,竟然是用.net写的,下意识地Reflector了一下.发现竟是一个叫actmp的程序集.如图: ...