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();
??????? }
??? }
}
?
神奇的输出:
?
赤
橙
黄
赤
橙
黄
赤
橙
黄
赤
橙
黄
赤
橙
黄
赤
橙
黄
赤
橙
黄
赤
橙
黄
赤
橙
黄
赤
橙
黄
赤