状态模式
状态(State)模式:对有状态的对象,把复杂的"判断逻辑"提取到不同的状态对象中,允许状态对象在其内部状态发生改变时改变其行为。
案例
模拟不同的上课状态转换:
java
public interface ClassState {
void study();
ClassState next();
}
java
public class MathClassState implements ClassState{
@Override
public void study() {
System.out.println("数学课想睡觉");
}
@Override
public ClassState next() {
return new PEClassState();
}
}
java
public class PEClassState implements ClassState{
@Override
public void study() {
System.out.println("体育课打起精神");
}
@Override
public ClassState next() {
return new AfterClassState();
}
}
java
public class AfterClassState implements ClassState{
@Override
public void study() {
System.out.println("放学了很开心");
}
@Override
public ClassState next() {
return new MathClassState();
}
}
java
public class Student {
private ClassState state;
public Student(ClassState state){
this.state = state;
}
public void study(){
state.study();
}
public void nextState(){
this.state = state.next();
}
}
测试:
java
public class Main {
public static void main(String[] args) {
Student student = new Student(new MathClassState());
student.study();
student.nextState();
student.study();
student.nextState();
student.study();
}
}