本文主要是介绍设计说明-行为型-状态模式-State,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
状态接口
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;}
}
这篇关于设计说明-行为型-状态模式-State的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!