当前位置:嗨网首页>书籍在线阅读

05-结果分析

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

结果分析

如果要实现一个存储人的姓和名的类,则它通常如下所示:

public class PersonMutable {
  private String firstName;
  private String lastName;
  private Date birthDate;
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  public Date getBirthDate() {
    return birthDate;
  }
  public void setBirthDate(Date birthDate) {
    this.birthDate = birthDate;
  }
}

遵循前文阐述的规则,将其转换成不可变类。结果如下:

public final class PersonImmutable {
  final private String firstName;
  final private String lastName;
  final private Date birthDate;
  public PersonImmutable (String firstName, String lastName,
                          String address, Date birthDate) {
    this.firstName=firstName;
    this.lastName=lastName;
    this.birthDate=birthDate;
  }
  public String getFirstName() {
    return firstName;
  }
  public String getLastName() {
    return lastName;
  }
  public Date getBirthDate() {
    return new Date(birthDate.getTime());
  }
}

该类遵循了不可变类的基本原则。

  • 类是 final 的。
  • 属性是 privatefinal 型的。
  • 属性值只能在类的构造器中设置。类的方法只返回属性的值,不能修改。
  • 对于可变属性(例子中的 birthDate 属性),需要在其 get() 方法中创建新对象,作保护性副本返回。