遇到多个构造器参数时要考虑用构建器
来源:互联网 发布:数学英文词典软件 编辑:程序博客网 时间:2024/04/30 06:31
1.当一个类有很多参数,其中一些是必须的,一些是可选的时候,使用构建器清晰明了:
下面的类可以修改为构造器
/** * Created by kaizige on 2017/7/3. */public class Person { private int age;//必须 private String name;//必须 private String sex;//必须 private String father; private String mother; public Person(int age, String name, String sex, String father, String mother) { this.age = age; this.name = name; this.sex = sex; this.father = father; this.mother = mother; } public Person(int age, String name, String sex,String father){ this(age,name,sex,father,null); } public Person(int age, String name, String sex){ this(age,name,sex,null,null); }}/** * Created by kaizige on 2017/7/3. */public class Person2 { private int age;//必须 private String name;//必须 private String sex;//必须 private String father; private String mother; @Override public String toString() { return "Person2{" + "age=" + age + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", father='" + father + '\'' + ", mother='" + mother + '\'' + '}'; } public Person2(Builder builder){ this.age=builder.age; this.name=builder.name; this.father=builder.father; this.mother=builder.mother; this.sex=builder.sex; } public static class Builder{ private int age;//必须 private String name;//必须 private String sex;//必须 private String father=null; private String mother=null; public Builder(int age, String name, String sex){ this.age = age; this.name = name; this.sex = sex; } public Builder withFather(String father){ this.father=father; return this; } public Builder withMother(String mother){ this.mother=mother; return this; } public Person2 build(){ return new Person2(this); } } public static void main(String[] args) { System.out.println(new Builder(22,"杨凯","男").withFather("杨").withMother("王").build()); }}
阅读全文
0 0
- Effective Java第二条:遇到多个构造器参数时要考虑用构建器
- 第2条:遇到多个构造器参数时要考虑用构建器
- 02、遇到多个构造器参数时要考虑用构建器
- Effective Java (2) - 遇到多个构造器参数时要考虑用构建器
- 第2条:遇到多个构造器参数时要考虑用构建器
- 第2条:遇到多个构造器参数时要考虑用构建器
- 遇到多个构造器参数时要考虑用构建器
- 第2条:遇到多个构造器参数时要考虑用构建器
- Effective Java 第二条:遇到多个构造器参数时要考虑用构建器
- 第二条:遇到多个构造器参数时要考虑用构建器
- Effective-Java学习笔记 遇到多个构造器参数时要考虑用构建器
- effective java(一)遇到多个构造器参数 时要考虑用构建器
- 第二条:遇到多个构造器参数时要考虑用构建器
- 02-遇到多个构造器参数时要考虑用构建器
- EffectiveJava-2.遇到多个构造器参数时要考虑用构建器
- 第2条 遇到多个构造器参数时要考虑用构建器
- 第2条:遇到多个构造器参数时要考虑用构建器
- 遇到多个构造器参数时要考虑用构建器
- 富文本的使用之二 设置TextView不同字段的颜色和背景颜色
- swift 访问权限
- java中set和get方法的理解
- 数字颠倒
- html学习的一些笔记
- 遇到多个构造器参数时要考虑用构建器
- Matplotlib库入门
- 《算法》第四版中文——学习资料
- 如何通过反射访问私有变量和私有方法
- 设计模式(八)abstruct factory
- nutz
- iOS
- xxx is not in the sudoers file.This incident will be reported.的解决方法
- HTTP协议详解(真的真的很经典)