设计模式之状态模式(state)
根据内部状态的变化,改变对象的行为。既改变对象的状态,又改变对象的行为
状态模式(State)为行为型
Java 设计模式之状态模式(state)示例
- 定义状态接口类
public interface State {
public String getState();
public void doHandler(Context context);
}
- 上下文环境
public class Context {
private State currentState;
public void setState(State state)
{
this.currentState = state;
}
public void logState()
{
if(currentState == null)
{
LogHelper.log("当前风扇未运行..." );
}
else if(currentState.getState().equalsIgnoreCase("0"))
{
LogHelper.log("当前风扇已停止..." );
}
else
{
LogHelper.log("当前风扇状态: " +currentState.getState());
}
}
}
- 定义状态1
//
public class StateOne implements State{
@Override
public String getState() {
return "1";
}
@Override
public void doHandler(Context context) {
LogHelper.log("风扇" + getState() + "档转速中....");
context.setState(this);
}
}
- 定义状态2
public class StateTwo implements State{
@Override
public String getState() {
return "2";
}
@Override
public void doHandler(Context context) {
LogHelper.log("风扇" + getState() + "档转速中....");
context.setState(this);
}
}
- 定义状态3
public class StateThree implements State{
@Override
public String getState() {
return "3";
}
@Override
public void doHandler(Context context) {
LogHelper.log("风扇" + getState() + "档转速中....");
context.setState(this);
}
}
- 定义停止状态
public class StateStop implements State{
@Override
public String getState() {
return "0";
}
@Override
public void doHandler(Context context) {
LogHelper.log("风扇未运行...");
context.setState(this);
}
}
- 测试类
public class App {
public static void main(String[] args)
{
Context context = new Context();
context.logState();
StateOne one = new StateOne();
one.doHandler(context);
context.logState();
StateTwo two = new StateTwo();
two.doHandler(context);
context.logState();
StateThree three = new StateThree();
three.doHandler(context);
context.logState();
StateStop stop = new StateStop();
stop.doHandler(context);
context.logState();
}
}
运行结果为
【www.pangugle.com】- 当前风扇未运行...
【www.pangugle.com】- 风扇1档转速中....
【www.pangugle.com】- 当前风扇状态: 1
【www.pangugle.com】- 风扇2档转速中....
【www.pangugle.com】- 当前风扇状态: 2
【www.pangugle.com】- 风扇3档转速中....
【www.pangugle.com】- 当前风扇状态: 3
【www.pangugle.com】- 风扇未运行...
【www.pangugle.com】- 当前风扇未停止...