状态模式:无非就是状态的改变
public class App {
public static void main(String[] args) {
Mammoth mammoth=new Mammoth();
mammoth.observe();
mammoth.timePasses();
mammoth.observe();
mammoth.timePasses();
mammoth.observe();
}
}
public interface State {
void onEnterState();
void observe();
}
public class AngryState implements State {
private Mammoth mammoth;
public AngryState(Mammoth mammoth){
this.mammoth=mammoth;
}
@Override
public void onEnterState() {
System.out.println(mammoth+" 暴怒了");
}
@Override
public void observe() {
System.out.println(mammoth+" 开始生气了!");
}
}
public class PeacefulState implements State{
private Mammoth mammoth;
public PeacefulState(Mammoth mammoth){
this.mammoth=mammoth;
}
@Override
public void onEnterState() {
System.out.println(mammoth+" 冷静和安详");
}
@Override
public void observe() {
System.out.println(mammoth+" 冷静下来了");
}
}
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();
}
@Override
public String toString() {
return "The mammoth";
}
public void observe(){
this.state.observe();
}
}
核心就是Mammoth这个类里面实现了逻辑切换了两个类