Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
class Currency {
  // total amount requested (required)
  private final int dollars;
  private final int cents;
  // change requested, denomination (optional)
  private final int quarters;
  private final int dimes;
  private final int nickels;
  private final int pennies;
  
  // Static class member 
  private Currency(Builder builder) {
    dollars = builder.dollars;
    cents = builder.cents;
   
    quarters = builder.quarters;
    dimes = builder.dimes;
    nickels = builder.nickels;
    pennies = builder.pennies;
  }

  // Static class member 
  public static class Builder {
    private final int dollars;
    private final int cents;
    private int quarters = 0;
    private int dimes = 0;
    private int nickels = 0;
    private int pennies = 0;
	 
    public Builder(int dollars, int cents) {
      this.dollars = dollars;
      this.cents = cents;
    }
    public Builder quarters(int quantity) {
      quarters = quantity;  
      return this; 
    }
    public Builder dimes(int quantity) {
      dimes = quantity; 
      return this;	 
    }
    public Builder nickles(int quantity) {
      nickels = quantity; 
      return this;	 
    }
    public Builder pennies(int quantity) {
      pennies = quantity; 
      return this;	 
    }
    public Currency build() {
      return new Currency(this); 	 
    }
  }
}

// Client code:
Currency USD = new Currency.Builder(10010,5650).quarters(2).nickles(1).pennies(142).build();

The idea is to call the constructor with the required parameters and obtain a builder object. Each optional parameter can be set using setters on the builder. The object construction concludes with the invocation of the build() method. This also has the effect of making the class Currency immutable.

...