状态模式定义:允许对象在内部状态发生改变时改变它的行为,对象看起来好像修改了它的类。
当代码中包含大量与对象状态有关的条件语句时,可以使用状态模式。
以下代码演示状态模式简单的实际运用:
定义一个接口State:
package com.ldl.cn.StateModel;
public interface State {
void doPlay(Context context);
}
定义一个类Context:
package com.ldl.cn.StateModel;
public class Context {
private State state;
public Context(){
state = null;
}
public Context(State state) {
super();
this.state = state;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
}
分别定义类PlayBasketballState、PlayFootballState实现State接口:
package com.ldl.cn.StateModel;
public class PlayBasketballState implements State{
@Override
public void doPlay(Context context) {
System.out.println("Start playing basketball.");
context.setState(this);
}
public String startBasketball(){
return "Basketball--start.";
}
}
package com.ldl.cn.StateModel;
public class PlayFootballState implements State{
@Override
public void doPlay(Context context) {
System.out.println("Start playing football.");
context.setState(this);
}
public String startFootball(){
return "Football--start.";
}
}
编写测试类:
package com.ldl.cn.StateModel;
public class TestStatePattern {
public static void main(String[] args) {
Context context = new Context();
PlayBasketballState playBasketballState = new PlayBasketballState();
playBasketballState.doPlay(context);
System.out.println(playBasketballState.startBasketball());
PlayFootballState playFootballState = new PlayFootballState();
playFootballState.doPlay(context);
System.out.println(playFootballState.startFootball());
}
}
运行结果:
Start playing basketball.
Basketball--start.
Start playing football.
Football--start.