状态接口
public interface State {//状态接口void insertQuarter();//投币void ejectQuarter();//退币void turnCrank();//按下“出纸巾”按钮void dispense();//出纸巾
}
有纸巾类
public class HasQuarterState implements State {private TissueMachine tissueMachine;@Overridepublic void insertQuarter() {}@Overridepublic void ejectQuarter() {tissueMachine.setState(tissueMachine.getNoQuarterState());}@Overridepublic void turnCrank() {}@Overridepublic void dispense() {}
}
没有纸巾类
public class NoQuarterState implements State {private TissueMachine tissueMachine;@Overridepublic void insertQuarter() {tissueMachine.setState(tissueMachine.getHasQuarterState());}@Overridepublic void ejectQuarter() {}@Overridepublic void turnCrank() {}@Overridepublic void dispense() {}
}
售完类
public class SoldOutState implements State {private TissueMachine tissueMachine;@Overridepublic void insertQuarter() {}@Overridepublic void ejectQuarter() {}@Overridepublic void turnCrank() {}@Overridepublic void dispense() {if (tissueMachine.getCount() > 0) {tissueMachine.setCount(tissueMachine.getCount() - 1);tissueMachine.setState(tissueMachine.getNoQuarterState());} else {tissueMachine.setState(tissueMachine.getSoldOutState());}}
}
售卖类
public class SoldState implements State {private TissueMachine tissueMachine;@Overridepublic void insertQuarter() {tissueMachine.setState(this);}@Overridepublic void ejectQuarter() {}@Overridepublic void turnCrank() {}@Overridepublic void dispense() {}
}
纸巾自动售货机类
@Getter
@Setter
public class TissueMachine {//纸巾售货机类private State soldOutState, noQuarterState, hasQuarterState, soldState, state;int count = 0;//纸巾数public TissueMachine(int count) {this.count = count;}
}