集册 Java实例教程 使用复制构造函数正确实现不可变的类

使用复制构造函数正确实现不可变的类

欢马劈雪     最近更新时间:2020-01-02 10:19:05

515
使用复制构造函数正确实现不可变的类
/**
来 自 时代Java - nowjava.com
**/

class MyClass {

  private final IntHolder valueHolder;


  public MyClass(int value) {

    this.valueHolder = new IntHolder(value);

  }


  public MyClass(IntHolder holder) {

    // Must make a copy of holder parameter

    this.valueHolder = new IntHolder(holder.getValue());

  }


  /* Rest of the code goes here... */

}/*来自 时代Java公众号*/


class IntHolder {

  private final int value;

  private int halfValue = Integer.MAX_VALUE;


  public IntHolder(int value) {

    this.value = value;

  }


  public int getValue() {

    return value;

  }


  public int getHalfValue() {

    // Compute half value if it is not already computed

    if (this.halfValue == 
展开阅读全文