public class 状态模式 { public static void main(String[] args) { Context context=new Context(); context.Request(); context.Request(); context.Request(); //System.out.println(context.getState()); context.Request(); context.Request(); } } class Context{ private int index; private State state; public Context() { index=3; state=new StateA(); } public void setIndex(int index) { this.index=index; } public void setState(State state) { this.state=state; } public int getIndex() { return index; } public State getState() { return state; } public void Request() { state.Handle(this); } } interface State{ public void Handle(Context context); } class StateA implements State{ @Override public void Handle(Context context) { int index=context.getIndex(); if(index>=1) { System.out.println("购买成功"); index=index-1; context.setIndex(index); if(index==0) { context.setState(new StateB()); } }else System.out.println("购买失败"); } } class StateB implements State{ @Override public void Handle(Context context) { int index=context.getIndex(); if(index==0) { System.out.println("购买失败,需要补货"); index=index+5; System.out.println("补货成功,请重新购买"); context.setIndex(index); context.setState(new StateA()); } } }
运行结果
标签:状态,Context,index,软件设计,void,模式,state,context,public From: https://www.cnblogs.com/cinan/p/17800838.html