????2.?????????????

package stateMachine;
/**
* ??????????????????????????
* @author seacean
* @date 2013-8-29
*/
public class Machine {
//??????????????е?????
private State soldOutState;
private State noQuarterState;
private State hasQuarterState;
private State soldState;
private State state; //??????????
private int count = 0;//?????е???????????
/**
* ??????????????????е????????????????????????????????
* @param count
*/
public Machine(int count) {
this.soldOutState = new SoldOutState(this);
this.noQuarterState = new NoQuarterState(this);
this.hasQuarterState = new HasQuarterState(this);
this.soldState = new SoldState(this);
this.count = count;
if (this.count > 0) {
this.state = noQuarterState;
}
}
/**
* ???????????????????
*/
public void releaseBall() {
System.out.println("a gumball comes rolling out the solt...");
if (count > 0) {
count -= 1;
}
}
public void insertQuerter() {
state.insertQuarter();//???????
}
public void ejectQuarter() {
state.ejectQuarter();
}
public void turnCrank() {
state.turnCrank();
state.dispense();
}
public State getSoldOutState() {
return soldOutState;
}
public State getNoQuarterState() {
return noQuarterState;
}
public State getHasQuarterState() {
return hasQuarterState;
}
public State getSoldState() {
return soldState;
}
public State getState() {
return state;
}
public int getCount() {
return count;
}
public void setState(State state) {
this.state = state;
}
}
????3.?????????????Щ?????
package stateMachine;
/**
* ??????????????????
* @author seacean
* @date 2013-8-29
*/
public class NoQuarterState implements State {
private Machine machine;
public NoQuarterState(Machine machine) {
this.machine = machine;
}
@Override
public void insertQuarter() {
System.out.println("please insert a quarter!");
machine.setState(machine.getHasQuarterState());
}
@Override
public void ejectQuarter() {
System.out.println("please insert a quarter!");
}
@Override
public void turnCrank() {
System.out.println("please insert a quarter!");
}
@Override
public void dispense() {
System.out.println("please insert a quarter!");
}
}

 

package stateMachine;
/**
* ???????????????????????????????
* @author seacean
* @date 2013-8-29
*/
public class HasQuarterState implements State {
private Machine machine;
public HasQuarterState(Machine machine){
this.machine=machine;
}
@Override
public void insertQuarter() {
System.out.println("You can not insert another quarter!");
}
@Override
public void ejectQuarter() {
System.out.println("Quarter returned!");
machine.setState(machine.getNoQuarterState());
}
@Override
public void turnCrank() {
System.out.println("You turned ... ");
machine.setState(machine.getSoldState());
}
@Override
public void dispense() {
System.out.println("No gumball dispensed!");
}
}

???????????????????????漰???????????????????SPASVOС??(021-61079698-8054)?????????????????????????