状态模式允许对象在内部状态改变时改变它的行为,对象看起来好像修改了他的类。
适用场景:
一个对象的行为取决于他的状态,并且它必须在运行时根据状态改变它的行为;
一个操作中含有庞大的多分支结构,并且这些分支决定于对象的状态。
类图:
模式的组成:
环境类Context: 定义客户感兴趣的接口。维护一个ConcreteState子类的实例,这个实例定义当前状态;
抽象状态类State: 定义一个接口以封装与Context的一个特定状态相关的行为;
具体状态类ConcreteState: 每一子类实现一个与Context的一个状态相关的行为;
实例:push显示红-〉黄-〉绿,pull显示绿-〉黄-〉红
public interface State
{
public void handlePush(Context context);
public void handlePull(Context context);
public String getColor();
}
public class Context
{
private State state = null;
public State getState()
{
return state;
}
public void setState(final State state)
{
this.state = state;
}
public void push()
{
state.handlePush(this);
}
public void pull()
{
state.handlePull(this);
}
}
//RED
public class ConcreteStateA implements State
{
@Override
public void handlePush(final Context context)
{
System.out.print(this.getColor());
final State state = new ConcreteStateB();
context.setState(state);
state.handlePush(context);
}
@Override
public void handlePull(final Context context)
{
System.out.print(this.getColor());
}
@Override
public String getColor()
{
return "RED";
}
}
//YELLOW
public class ConcreteStateB implements State
{
@Override
public void handlePush(final Context context)
{
System.out.print(this.getColor());
final State state = new ConcreteStateC();
context.setState(state);
state.handlePush(context);
}
@Override
public void handlePull(final Context context)
{
System.out.print(this.getColor());
final State state = new ConcreteStateA();
context.setState(state);
state.handlePull(context);
}
@Override
public String getColor()
{
return "YELLOW";
}
}
//green
public class ConcreteStateC implements State
{
@Override
public void handlePush(final Context context)
{
System.out.print(this.getColor());
}
@Override
public void handlePull(final Context context)
{
System.out.print(this.getColor());
final State state = new ConcreteStateB();
context.setState(state);
state.handlePull(context);
}
@Override
public String getColor()
{
return "GREEN";
}
}
public class Client
{
public static void main(final String[] args)
{
// YTODO Auto-generated method stub
final Context context = new Context();
context.setState(new ConcreteStateA());
System.out.println("PUSH:");
context.push();
System.out.println("\nPULL:");
context.pull();
}
}
结果:
PUSH:
REDYELLOWGREEN
PULL:
GREENYELLOWRED