天天看點

設計模式(二十一) 狀态模式

狀态模式也是一種行為型模式,當我們的程式中需要一些狀态轉換,對于不同的狀态需要不同的行為時,我們就可以考慮使用狀态模式。

下面用交通燈來當例子。我們需要紅黃綠三種顔色的狀态。

interface State {
    void show();
}

class RedState implements State {

    @Override
    public void show() {
        System.out.println("交通燈變紅了");

    }
}

class YellowState implements State {

    @Override
    public void show() {
        System.out.println("交通燈變黃了");

    }
}

class GreenState implements State {

    @Override
    public void show() {
        System.out.println("交通燈變綠了");

    }
}
           

然後需要交通燈,它作為狀态類的環境,内部應該有所有狀态類的執行個體,并能按照某種規則轉換狀态。

public class TrafficLight {
    private State redState = new RedState();
    private State yellowState = new YellowState();
    private State greenState = new GreenState();

    private State current = greenState;

    public void turn() {
        if (current == greenState) {
            current = yellowState;
            current.show();
        } else if (current == yellowState) {
            current = redState;
            current.show();
        } else {
            current = greenState;
            current.show();
        }
    }
}
           

然後客戶類不需要關心内部狀态的變化,就可以使用狀态類了。

public void run() {
        TrafficLight light = new TrafficLight();
        light.turn();
        light.turn();
        light.turn();
        light.turn();
    }
           

繼續閱讀