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条:遇 ...
随机推荐
- LeetCode——LRU Cache
Description: Design and implement a data structure for Least Recently Used (LRU) cache. It should su ...
- .Net魔法堂:史上最全的ActiveX开发教程——发布篇
一. 前言 接着上一篇<.Net魔法堂:史上最全的ActiveX开发教程——开发篇>,本篇讲述如何发布我们的ActiveX. 二.废话少讲,马上看步骤! 1. 打包 C#开发的Activ ...
- MVC知识点01
1:母版页都 放在View/Shared里面,而且全部的视图页面都可以去用母板页. **母板的应用要用到嵌套,@RenderBody();将别的网页的内容全部显示在此处,它就相当于一个占位符. 2:架 ...
- C#开源资源项目
一.AOP框架 Encase 是C#编写开发的为.NET平台提供的AOP框架.Encase 独特的提供了把方面(aspects)部署到运行时代码,而其它AOP框架依赖配置文件的方式.这种部署方面(as ...
- 自定义饼图(PieChart)各个PieSlice的外观
C1Chart提供了Theme和Palette接口,其中内置了很多配色方案,调整外观. <c1chart:C1Chart Margin="0,0,8,8" MinHeight ...
- JPA学习(2)注解
上一篇学习了JPA的helloworld,也初略的使用了一些注解,接下来就细细的了解一下有哪些注解,和这些注解的作用 JPA的基本注解: ①@Entity,@Table,@Id,@GeneratedV ...
- [moka同学笔记]yii2场景的使用(摘录)
前半部分为自己使用的过程,下边为转载的,具体地址见:http://blog.sina.com.cn/s/blog_88a65c1b0101j717.html 1.在model中 public func ...
- IBATIS动态SQL(转)
直接使用JDBC一个非常普遍的问题就是动态SQL.使用参数值.参数本身和数据列都是动态SQL,通常是非常困难的.典型的解决办法就是用上一堆的IF-ELSE条件语句和一连串的字符串连接.对于这个问题,I ...
- 转收藏:Git常用命令速查表
一. Git 常用命令速查 git branch 查看本地所有分支git status 查看当前状态 git commit 提交 git branch -a 查看所有的分支git branch -r ...
- virtualenv and virtualenvwrapper on Ubuntu 14.04
In this post I’ll go over my attempt to setup virtual environments for Python development. Most Pyth ...