在状态模式(State Pattern)中,类的行为是基于它的状态改变的。过程中创建表示各种状态的对象和一个行为随着状态对象改变而改变的主体
状态接口
public interface State {
public void doAction(Context context);
}
两个状态
import java.util.Calendar;
public class Morning implements State{
@Override
public void doAction(Context context) {
Calendar cal=Calendar.getInstance();
if (cal.get(Calendar.HOUR) < 12) {
System.out.println("morning");
} else {
context.setState(new Noon());
}
}
}
public class Noon implements State {
@Override
public void doAction(Context context) {
System.out.println("Noon");
}
}
主体
public class Context {
private State state;
public Context(){
state = new Morning();
}
public void setState(State state){
this.state = state;
}
public State getState(){
return state;
}
public void work(){
state.doAction(this);
}
}
主函数
Context context = new Context();
context.setState(new Morning());
context.work();
...
context.work();