Advantage

  1. It simulates named optional parameters which is easily used to client API.
  2. Detect the invariant failure(validation error of field) as soon as the invalid parameters are passed, instead of waiting for build to be invoked.
  3. The builder can fill in some fields automatically such as a serial number.
  4. Avoid Class.newInstancebreaks compile-time exception checking

Disadvantage

  1. 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的更多相关文章

  1. Effective Java Item2:Consider a builder when faced with many constructor parameters

    Item2:Consider a builder when faced with many constructor parameters 当构造方法有多个参数时,可以考虑使用builder方式进行处理 ...

  2. 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 ...

  3. 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)实现单例模式. ...

  4. 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 ...

  5. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  6. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  7. Effective Java —— 多字段下考虑使用建造者模式构建实例

    本文参考 本篇文章参考自<Effective Java>第三版第二条"Consider a builder when faced with many constructor pa ...

  8. 《Effective Java》读书笔记 - 2.创建和销毁对象

    Chapter 2 Creating and Destroying Objects item 1:Consider static factory methods instead of construc ...

  9. Java之进阶(1) -《Effective Java》

    第1章 引言 第2章 创建和销毁对象 第1条:考虑用静态工厂方法代替构造器(Consider static factory methods instead of constructors) 第2条:遇 ...

随机推荐

  1. [python]初探socket

    1.什么是socket? Socket中文译作:套接字,但是大家一般约定俗称的都用:socket.我想在解释socket是什么之前,先说它是用来干嘛的:socket是来建立'通信'的基础,建立连接,传 ...

  2. Mysql大量插入随机数据方法--存储过程

    创建测试表: mysql)); 创建存储过程: mysql> delimiter // mysql> create procedure rand_data(in num int) -> ...

  3. Web性能

    使用Web性能测试可以很容易地创建一组可重复的测试,从而帮助我们分析web应用程序的性能,找到性能瓶颈. Web性能测试可以验证一个Web应用程序的行为是否正确.它们会向目标Web应用程序发布一组有序 ...

  4. Struts2的基本流程的详细介绍

    Struts2基本流程 概述: Struts2框架由三部分构成:核心控制器.业务控制器和用户实现的业务逻辑组件.在这三部分中,struts2框架提供了核心控制器StrutsPrepareAndExec ...

  5. dp - 2015 Multi-University Training Contest 2 1004 Delicious Apples

    Delicious Apples Problem's Link: http://acm.hdu.edu.cn/showproblem.php?pid=5303 Mean: 一条长为L的环形路上种着n棵 ...

  6. 重构第12天 分解依赖(Break Dependencies)

    理解:“分解依赖” 是指对部分不满足我们要求的类和方法进行依赖分解,通过装饰器来达到我们需要的功能. 详解:今天我们所讲的这个重构方法对于单元测试是非常有用的.如果你要在你的代码中加入单元测试但有一部 ...

  7. EasyUI组合树插件

    一.引用CSS和JS <link href="~js/easyui/easyui.css" rel="stylesheet" type="tex ...

  8. Winform开发框架之权限管理系统改进的经验总结(3)-系统登录黑白名单的实现

    在一般的权限系统里面,可能经常会看到系统的黑名单或者白名单的拦截功能.在一般权限系统里面,常见的黑名单就是禁止用户在某些IP上登录系统,白名单就是允许用户只在某些IP上登录系统.本随笔主要介绍在我的权 ...

  9. AC自动机---病毒侵袭

    HDU 2896 题目网址: http://acm.hust.edu.cn/vjudge/contest/view.action?cid=110773#problem/B Description 当太 ...

  10. Durandal介绍

         Durandal是一个JS框架用于构建客户端single page application(SPAs).它支持MVC,MVP与MVVM前端构架模式.使用RequireJS做为其基本约定层,D ...