package candy; import java.lang.reflect.Constructor; /** * A candy machine that has the capacity of N basic candy machines. * by a base machine. * * @author CSC223 2004F * @version 0.0 of August 2004 */ public class BiggerCandyMachine0 implements CandyMachine { // +--------+------------------------------------------------------------ // | Fields | // +--------+ int machinesLeft = 5; CandyMachine base; // +--------------+------------------------------------------------------ // | Constructors | // +--------------+ public BiggerCandyMachine0(CandyMachine _base) { this.base = _base; // Thanks Jesse! } // BiggerCandyMachine0(CandyMachine) // +----------+---------------------------------------------------------- // | Mutators | // +----------+ public String get() throws CandyMachineException { // Build a new machine, if necessary if (this.base.isEmpty() && this.machinesLeft > 0) { this.base = this.newMachine(); --this.machinesLeft; } return base.get(); } // get() // +-----------+--------------------------------------------------------- // | Observers | // +-----------+ public boolean isEmpty() { // For the bigger machine to be empty, we need // no other machines left and the base machine to // be empty. return (this.machinesLeft == 0) && this.base.isEmpty(); } // isEmpty() // +-------+------------------------------------------------------------- // | Local | // +-------+ private CandyMachine newMachine() throws CandyMachineException { try { Class baseClass = base.getClass(); Constructor cons = baseClass.getConstructor(null); return (CandyMachine) cons.newInstance(null); } catch (Exception e) { throw new CandyMachineException(e.toString()); // Hack! } } // newMachine() } // class BiggerCandyMachine0