A Immutable Version of the IntHolderWrapper Class - Java Object Oriented Design

Java examples for Object Oriented Design:Class

Description

A Immutable Version of the IntHolderWrapper Class

Demo Code

class MyClass {/*from w  ww. j av  a2s .  c om*/
  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();
  }
}

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 == Integer.MAX_VALUE) {
      // Cache the half value for future use
      this.halfValue = this.value / 2;
    }
    return this.halfValue;
  }
}

Related Tutorials