自学内容网 自学内容网

状态模式

状态模式

状态(State)模式:对有状态的对象,把复杂的“判断逻辑”提取到不同的状态对象中,允许状态对象在其内部状态发生改变时改变其行为。

案例

模拟不同的上课状态转换:

public interface ClassState {
    void study();
    ClassState next();
}
public class MathClassState implements ClassState{
    @Override
    public void study() {
        System.out.println("数学课想睡觉");
    }

    @Override
    public ClassState next() {
        return new PEClassState();
    }
}
public class PEClassState implements ClassState{
    @Override
    public void study() {
        System.out.println("体育课打起精神");
    }

    @Override
    public ClassState next() {
        return new AfterClassState();
    }
}
public class AfterClassState implements ClassState{
    @Override
    public void study() {
        System.out.println("放学了很开心");
    }

    @Override
    public ClassState next() {
        return new MathClassState();
    }
}
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();
    }
}

测试:

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();
    }
}

原文地址:https://blog.csdn.net/weixin_74144099/article/details/142516619

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!