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条:遇 ...
随机推荐
- 直接拿来用!最火的Android开源项目
GitHub在中国的火爆程度无需多言,越来越多的开源项目迁移到GitHub平台上.更何况,基于不要重复造轮子的原则,了解当下比较流行的Android与iOS开源项目很是必要.利用这些项目,有时能够让你 ...
- 好用的ASP.NET 分页类 简单好用 支持 AJAX 自定义文字
在做网站没用 JS UI控件时 很实用 用法: var ps=new PageString(); /*可选参数*/ ps.SetIsEnglish = true;// 是否是英文 (默认:false) ...
- 一个android应用开发的感悟
对于客户端的开发,以我个人现在的水准,很难进行一个系统的讲解,只能分享下遇到的几个问题点好了! 1:对于tabhost的使用,这个东西真的是过时了:第一个版本,我是用的tabhost确实是很难用,不过 ...
- Linux的Cgroup
为什么要有cgroup Linux系统中经常有个需求就是希望能限制某个或者某些进程的分配资源.也就是能完成一组容器的概念,在这个容器中,有分配好的特定比例的cpu时间,IO时间,可用内存大小等.于是就 ...
- CSS魔法堂:选择器及其优先级
一.前言 首先看看一道阿里这期网申的题目吧! 1.找出下面优先级相同的选择器 A. img.thumb:after B.[data-job="frontend"]::firs ...
- 一个关于explain出来为all的说明及优化
explain sql语句一个语句,得到如下结果,为什么已经创建了t_bill_invests.bid_id的索引,但却没有显示using index,而是显示all扫描方式呢,原来这还与select ...
- sql:Oracle11g 表,视图,存储过程结构查询
-- Oracle 11 G --20160921 涂聚文再次修改 --Geovin Du --GetTables SELECT owner, object_name, created FROM al ...
- WebGL/X3DOM 跑在 iOS
iOS是最早支持WebGL的移动操作系统之一,我们一直在努力让X3DOM运行在那些设备上.然而,标准的Safari浏览器默认是没有开启的.这种情况从iOS8发生改变,iOS8现在完全支持WebGL - ...
- HTML页面放大镜效果
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- jquery 回到 顶部
1. 页面内容较多, 从底部超链接 点击回到页面顶部 // 回到顶部 var $top = $('<a class="doc-gotop" href="javasc ...