遇到多个构造器参数时要考虑用构建器。
package Builder;
public class Student {
private final String name;
private final int id;
private final String sex;
private final String birth;
private final String home;
public static class Builder{
private String name;
private int id;
private String sex;
private String birth;
private String home;
public Builder setName(String name){
this.name = name;
return this;
}
public Builder setId(int id) {
this.id = id;
return this;
}
public Builder setSex(String sex) {
this.sex = sex;
return this;
}
public Builder setBirth(String birth) {
this.birth = birth;
return this;
}
public Builder setHome(String home) {
this.home = home;
return this;
}
public Student builder(){
return new Student(this);
}
}
private Student(Builder builder){
this.name = builder.name;
this.sex = builder.sex;
this.id = builder.id;
this.birth = builder.birth;
this.home = builder.home;
}
public String toString(){
return this.name + "'s sex is " + this.sex + "," + this.id + "," + this.home;
}
public static void main(String[] args){
Student s = new Student.Builder().setName("zoe").setSex("Female").setId(1016).setHome("No").builder();
System.out.println(s);
}
}
分享到:
相关推荐
《Effective Java》第三版中文版目录 第一章 介绍 1 第二章 创建和销毁对象 4 1 考虑用静态工厂方法替换构造器 4 2 当遇到多个构造器参
effective java 读书笔记,第二版自己摘要并翻译,以备速查。
[Addison-Wesley] Effective Java 第2版 (英文版) [Addison-Wesley] Effective Java 2nd Edition (E-Book) ☆ 出版信息:☆ [作者信息] Joshua Bloch [出版机构] Addison-Wesley [出版日期] 2008年05月28日 ...
java effective 第二版中英文二份文件,包含本书源码。
Item 85: Prefer alternatives to Java serialization Item 86: Implement Serializable with great caution Item 87: Consider using a custom serialized form Item 88: Write readObject methods defensively ...
Effective-Java Effective Java中文版第二版示例代码
Effective C++ 第2版 超级高清 (中文版)
Effective C++第二版与第三版差别有点大。总的来说,第二版更适合C语言转向C++的初学者,第三版更适合Java等语言转向C++的初学者。由于网络上和书店里大多是第三版的中文版。考虑到大部分以C作为基础语言的学生们,...
基于Effective Java第二版的读书笔记,可以帮助你更好的阅读这边Java圣经,更快的理解其思想
Intellij 的有效 Java 重构 该插件旨在为 Intellij 提供重构操作,以实现 Effective Java,第 2 版中讨论的模式。
有效的 Java(第 2 版)示例
第 2 条:当面临许多构造函数参数时考虑构建器 伸缩构造函数模式有效,但是当参数很多时很难编写客户端代码,而且更难阅读 Builder 模式模拟命名的可选参数 Class.newInstance 破坏编译时异常检查 在设计具有构造...
java逻辑思维笔试题Effective Java - 第三版笔记 章节索引 02 - 创建和销毁对象 03 - 所有对象通用的方法 04 - 类和接口 05 - 泛型 06 - 枚举和注释 07 - Lambda 和流 08 - 方法 09 - 通用编程 10 - 例外 11 - 并发 ...
effective第三版是英文 出版日期差不多在java8版本,effective第二版是中文,出版日期差不多在java5版本
为反映出现代设计考虑,对第二版论题做了广泛的修订,包括异常(exceptions)、设计模式(design patterns)和多线程(multithreading)。 《effective c++》的重要特征包括: * 高效的 classes、functions、...
Java EE Development with Eclipse(2nd) 英文azw3 第2版 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
为反映出现代设计考虑,对第二版论题做了广泛的修订,包括异常(exceptions)、设计模式(design patterns)和多线程(multithreading)。 《Effective C++》的重要特征包括: * 高效的 classes、functions、...
第2章对象的创建和销毁 项目编号 标题 副标题 经理 项目1 项目2 项目3 项目4 项目5 不要直接指定资源,请使用依赖对象注入 莉娜 项目6 避免不必要的对象创建 德玛 项目7 释放使用的对象参考 莉娜 项目8 避免使用...