State パターン

State パターン

MyMain

public class MyMain {
    public static void main(String args[]) {
        MyContext context = new MyContext();
        context.changeState(MyStateNight.getInstance());

        for (int i = 0; i <= 24; i++) {
            System.out.print(i);
            System.out.println("時");
            // 状態を変更するタイミングは、Context クラスではなく、
            // State クラスが決定する
            context.setClock(i);
        }
    }
}

MyContext

public class MyContext {
    public MyState state;

    public MyContext() {
        state = MyStateDay.getInstance();
    }
    // 状態を変化させる処理は、State クラスから呼ばれる
    public void changeState(MyState state) {
        System.out.println(state.toString() + "です");
        this.state = state;
    }
    public void setClock(int h) {
        state.setClock(this, h);
    }
}

MyState

public interface MyState {
    public void    setClock(MyContext context, int h);
    public String  toString();
}

MyStateDay

public class MyStateDay implements MyState {
    private static MyState state = new MyStateDay();
    private MyStateDay () {
    }
    public static MyState getInstance() {
        return state;
    }

    public void setClock(MyContext context, int h) {
        if (h < 6 || 18 <= h)
            context.changeState(MyStateNight.getInstance());
    }
    public String toString() {
        return "昼";
    }
}

MyStateNight

public class MyStateNight implements MyState {
    private static MyState state = new MyStateNight();
    private MyStateNight () {
    }
    public static MyState getInstance() {
        return state;
    }

    public void setClock(MyContext context, int h) {
        if (6 <= h && h < 18)
            context.changeState(MyStateDay.getInstance());
    }
    public String toString() {
        return "夜";
    }
}

実行結果

L:\>java MyMain
夜です
0時
1時
2時
3時
4時
5時
6時
昼です
7時
8時
9時
10時
11時
12時
13時
14時
15時
16時
17時
18時
夜です
19時
20時
21時
22時
23時
24時