状态模式(State DP)允许对象在内部状态改变时改变行为,就好像换了一个类一样(原文:Allow an object to alter its behavior when its internal state changes. The object will appear to change its class)。
说起状态模式,就不得不提策略模式。两者都是在运行时可以改变行为,不同的是,策略模式是用户自己临时选择,而状态模式是用户之前定义好状态的转换,运行时根据既定的状态机来执行转换。当然,如果非得手动控制状态,那这两个模式确实很接近。
代码:
State接口:
/**
*
* State interface.
*
*/
public interface State {
void onEnterState();
void observe();
}
猛犸:
/**
*
* Mammoth has internal state that defines its behavior.
*
*/
public class Mammoth {
private State state;
public Mammoth() {
state = new PeacefulState(this);
}
/**
* Makes time pass for the mammoth
*/
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();
}
@Override
public String toString() {
return "The mammoth";
}
public void observe() {
this.state.observe();
}
}
愤怒模式:
/**
*
* Angry state.
*
*/
public class AngryState implements State {
private static final Logger LOGGER = LoggerFactory.getLogger(AngryState.class);
private Mammoth mammoth;
public AngryState(Mammoth mammoth) {
this.mammoth = mammoth;
}
@Override
public void observe() {
LOGGER.info("{} is furious!", mammoth);
}
@Override
public void onEnterState() {
LOGGER.info("{} gets angry!", mammoth);
}
}
平静模式:
/**
*
* Peaceful state.
*
*/
public class PeacefulState implements State {
private static final Logger LOGGER = LoggerFactory.getLogger(PeacefulState.class);
private Mammoth mammoth;
public PeacefulState(Mammoth mammoth) {
this.mammoth = mammoth;
}
@Override
public void observe() {
LOGGER.info("{} is calm and peaceful.", mammoth);
}
@Override
public void onEnterState() {
LOGGER.info("{} calms down.", mammoth);
}
}
测试:
public static void main(String[] args) {
Mammoth mammoth = new Mammoth();
mammoth.observe();
mammoth.timePasses();
mammoth.observe();
mammoth.timePasses();
mammoth.observe();
}