集册 Java实例教程 IntHolderWrapper类的不可变版本

IntHolderWrapper类的不可变版本

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

550
IntHolderWrapper类的不可变版本

class MyClass {
/**
时 代 J a v a 公 众 号 - N o w J a v  a . c o m 提供 
**/

  private final IntHolder valueHolder;


  public MyClass(int value) {

    this.valueHolder = new IntHolder(value);

  }


  public IntHolder getIntHolder() {

    // Make a copy of valueHolder

    int v = this.valueHolder.getValue();

    IntHolder copy = new IntHolder(v);


    // Return the copy instead of the original

    return copy;

  }


  public int getValue() {

    return this.valueHolder.getValue();

  }/** n o w j a   v  a . c o m - 时  代  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 (
展开阅读全文