状态模式:一个对象的内部状态发生改变会引起行为的改变,此种变化会引起类的变化
优点:避免过多的if-else语句,扩展性良好,有很强的封装性
标注类图:
模拟电梯状态行为:
电梯类:
public class Lift {
public static final LiftOpenState OPEN_STATE = new LiftOpenState();
public static final LiftCloseState CLOSE_STATE = new LiftCloseState();
public static final LiftStopState STOP_STATE = new LiftStopState();
public static final LiftRunState RUN_STATE = new LiftRunState();
private LiftState currentState;
public LiftState getCurrentState() {
return currentState;
}
public void setCurrentState(LiftState currentState) {
this.currentState = currentState;
this.currentState.setLift(this);
}
public void open(){
currentState.open();
}
public void close(){
currentState.close();
}
public void stop(){
currentState.stop();
}
public void run(){
currentState.run();
}
}
抽象状态类:
public abstract class LiftState {
protected Lift lift;
public void setLift(Lift lift){
this.lift = lift;
}
protected abstract void open();
protected abstract void close();
protected abstract void stop();
protected abstract void run();
}
具体状态类:
public class LiftOpenState extends LiftState{
@Override
public void open() {
System.out.println("open");
}
@Override
public void close() {
super.lift.setCurrentState(Lift.CLOSE_STATE);
super.lift.close();
}
@Override
public void stop() {
super.lift.setCurrentState(Lift.STOP_STATE);
super.lift.stop();
}
@Override
public void run() {
super.lift.setCurrentState(Lift.RUN_STATE);
super.lift.run();
}
}
public class LiftCloseState extends LiftState{
@Override
public void open() {
super.lift.setCurrentState(Lift.OPEN_STATE);
super.lift.open();
}
@Override
public void close() {
System.out.println("close");
}
@Override
public void stop() {
super.lift.setCurrentState(Lift.STOP_STATE);
super.lift.stop();
}
@Override
public void run() {
super.lift.setCurrentState(Lift.RUN_STATE);
super.lift.run();
}
}
public class LiftStopState extends LiftState{
@Override
public void open() {
super.lift.setCurrentState(Lift.OPEN_STATE);
super.lift.open();
}
@Override
public void close() {
super.lift.setCurrentState(Lift.CLOSE_STATE);
super.lift.close();
}
@Override
public void stop() {
System.out.println("stop");
}
@Override
public void run() {
super.lift.setCurrentState(Lift.RUN_STATE);
super.lift.run();
}
}
public class LiftRunState extends LiftState{
@Override
public void open() {
super.lift.setCurrentState(Lift.OPEN_STATE);
super.lift.open();
}
@Override
public void close() {
super.lift.setCurrentState(Lift.CLOSE_STATE);
super.lift.close();
}
@Override
public void stop() {
super.lift.setCurrentState(Lift.STOP_STATE);
super.lift.stop();
}
@Override
public void run() {
System.out.println("run");
}
}
场景类:
public class Client {
public static void main(String[] args) {
Lift lift = new Lift();
lift.setCurrentState(Lift.OPEN_STATE);
lift.stop();
}
}
高层调用者不用关心状态的变化引起的行为的变化,而只是关注于具体的行为,具体的状态实现状态的过渡