JAVA枚举类实现状态机

直接上DEMO:

public enum OrderStateMachine {
	/**
	 * 调度中
	 */
	DISPATCHING {
		@Override
		public OrderStateMachine nextState() {
			return DELIVERING;
		}

		@Override
		public OrderStateMachine preState() {
			return this;
		}
	},
	/**
	 * 投递中
	 */
	DELIVERING {

		@Override
		public OrderStateMachine nextState() {
			return RECEIVED;
		}

		@Override
		public OrderStateMachine preState() {
			return DISPATCHING;
		}
		
	},
	/**
	 * 已收货
	 */
	RECEIVED {

		@Override
		public OrderStateMachine nextState() {
			return RECEIVED;
		}

		@Override
		public OrderStateMachine preState() {
			return DELIVERING;
		}
		
	};
	
	public abstract OrderStateMachine nextState();
	public abstract OrderStateMachine preState();
	
}

测试方法:

public class OrderStateMachineTest {
	public static void main(String[] args) {
		OrderStateMachine orderStateMachine = OrderStateMachine.DISPATCHING;
		System.out.println(orderStateMachine.nextState().nextState());
	}

}

 

你可能感兴趣的:(java)