重点等级::star:
- 替代 if ... else 。把复杂的“判断逻辑”提取到不同的状态对象中,允许状态对象在其内部状态发生改变时改变其行为
- 对象的行为取决于其状态,并且必须根据该状态在运行时更改其行为
//各种动物的不同状态所对应不一样的处理
//状态接口类
public interface State {
void onEnterState();
void observe();
}
//安静状态实现类
public class PeacefulState implements State {
private static final Logger LOGGER = LoggerFactory.getLogger(PeacefulState.class);
private final Animal animal;
public PeacefulState(Animal animal) {
this.animal = animal;
}
@Override
public void observe() {
LOGGER.info("{} 平静祥和.", animal);
}
@Override
public void onEnterState() {
LOGGER.info("{} 安静下来.", animal);
}
}
public class AngryState implements State {
private static final Logger LOGGER = LoggerFactory.getLogger(AngryState.class);
private final Animal animal;
public AngryState(Animal animal) {
this.animal = animal;
}
@Override
public void observe() {
LOGGER.info("{} 更生气了!", animal);
}
@Override
public void onEnterState() {
LOGGER.info("{} 生气了!", animal);
}
}
public class Animal {
private State state;
private String name;
public Animal(String name) {
this.name = name;
this.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();
}
@Override
public String toString() {
return name;
}
public void observe() {
this.state.observe();
}
}
var animal = new Animal("小猫");
animal.observe();
animal.timePasses();
animal.observe();
animal.timePasses();
animal.observe();
//小猫 平静祥和.
//小猫 生气了!
//小猫 更生气了!
//小猫 安静下来.
//小猫 平静祥和.