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