欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 状态模式

程序员文章站 2022-07-12 20:35:14
...

public class Context {
    private TestState testState;
    public void setState(TestState state){
        this.testState = state;
    }
    public void changeColor() {
        testState.handle();
    }
}

 

public interface TestState {
   void handle();
}

public class TestState1 implements TestState {
    private Context context;

    public TestState1(Context context) {
        this.context = context;
    }

    @Override
    public void handle() {
        System.out.println("赤");
        context.setState(new TestState2(context));
    }
}

public class TestState2 implements TestState {
    private Context context;

    public TestState2(Context context) {
        this.context = context;
    }

    @Override
    public void handle() {
        System.out.println("橙");
        context.setState(new TestState3(context));
    }
}

 

public class TestState3 implements TestState {
    private Context context;

    public TestState3(Context context) {
        this.context = context;
    }
    @Override
    public void handle() {
        System.out.println("黄");
        context.setState(new TestState1(context));
    }
}

 

public class Client {
    public static void main(String[] args) {
        Context context = new Context();
        context.setState(new TestState1(context));
        for (int i = 0; i < 100; i++) {
            context.changeColor();
        }
    }
}

 

神奇的输出: