目的:
允许对象在内部状态改变时改变它的行为。对象看起来好像修改了它的类。状态模式是一种允许对象在内部状态改变时改变它的行为的行为型设计模式。这种模式接近于有限状态机的概念。状态模式可以被理解为策略模式,它能够通过调用在模式接口中定义的方法来切换策略。
程序示例:
当在长毛象的自然栖息地观察长毛象时,似乎它会根据情况来改变自己的行为。它开始可能很平静但是随着时间推移当它检测到威胁时它会对周围的环境感到愤怒和危险。
1.定义状态和不同的实现类
public interface State{
void onEnterState();
void observer();
}
@Slf4j
public class PeacefulState implements State{
private final Mammoth mammoth;
public PeacefulState(Mammoth mammoth) {
this.mammoth = mammoth;
}
@Override
public void onEnterState() {
log.info("{} calms down.", mammoth);
}
@Override
public void observer() {
log.info("{} is calm and peaceful.", mammoth);
}
}
@Slf4j
public class AngryState implements State{
private final Mammoth mammoth;
public AngryState(Mammoth mammoth) {
this.mammoth = mammoth;
}
@Override
public void onEnterState() {
log.info("{} gets angry!", mammoth);
}
@Override
public void observer() {
log.info("{} is furious!", mammoth);
}
}
2.定义猛犸象类
public class Mammoth{
private State state;
public Mammoth() {
state=new PeacefulState(this);
}
//更改状态
public void timePasses(){
if (state.getClass().equals(PeacefulState.class)){
changeStateTo(new AngryState(this));
}else {
changeStateTo(new PeacefulState(this));
}
}
private void changeStateTo(State newState){
this.state=newState;
this.state.onEnterState();
}
public void observer(){
this.state.observer();
}
@Override
public String toString() {
return "The Mammoth";
}
}
3.测试输出
Mammoth mammoth = new Mammoth();
mammoth.observer();
mammoth.timePasses();
mammoth.observer();
mammoth.timePasses();
mammoth.observer();
/*
The Mammoth is calm and peaceful.
The Mammoth gets angry!
The Mammoth is furious!
The Mammoth calms down.
The Mammoth is calm and peaceful.
*/
类图:

文章通过状态模式展示了猛犸象在和平与愤怒两种状态之间的切换。猛犸象类包含一个状态接口,有两个实现类:和平状态和愤怒状态。随着时间的推移,猛犸象的状态会发生变化,其行为也随之改变,类似于有限状态机或策略模式的应用。

被折叠的 条评论
为什么被折叠?



