一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
状态模式主要解决,当控制一个对象状态的条件表达式过于复杂时的情况;把状态的判断逻辑转移到表示不同状态的一系列类中,可以把复杂的判断逻辑简化;
状态模式的角色:
上下文环境(Context)角色、抽象状态(State)角色、具体状态(Concrete State)和客户端(Client)角色;
状态模式的案例:
实现类图:

实现代码:
/**  * 上下文环境(Context)角色  */ public class Context { 	 	private State state;  	public Context() { 		state = null; 	}  	public void setState(State state) { 		this.state = state; 	}  	public State getState() { 		return state; 	} 	 }/**  * 抽象状态(State)角色  */ public interface State { 	    public void doAction(Context context);     }/**  * 具体状态(Concrete State)  */ public class StartState implements State {  	public void doAction(Context context) { 		System.out.println("Player is in start state."); 		context.setState(this); 	}  	public String toString() { 		return "Start State"; 	}  }/**  * 具体状态(Concrete State)  */ public class StopState implements State {  	public void doAction(Context context) { 		System.out.println("Player is in stop state."); 		context.setState(this); 	}  	public String toString() { 		return "Stop State"; 	} }/**  * 客户端  */ public class Client {  	public static void main(String[] args) { 		Context context = new Context();  		StartState startState = new StartState(); 		startState.doAction(context); 		System.out.println(context.getState().toString());  		StopState stopState = new StopState(); 		stopState.doAction(context); 		System.out.println(context.getState().toString());  	}  }