// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
public class DemoStatePattern {
    public static void main(String[] args) {
        Car c = new Car();
        System.out.println(c);
        c.start();
        System.out.println(c);
        c.stop();
        System.out.println(c);
        c.stop(); // this will throw an exception
    }
}

class Car {
    private State st;
    public Car() {
        st = HoldState.INSTANCE;
    }
    void ChangeState(State st) {
        this.st = st;
    }
    public void start() {
        st.start(this);
    }
    public void stop() {
        st.stop(this);
    }
    public String toString() {
        return (st.getState() + " car");
    }
}

abstract class State {
    public void start(Car c) {
        throw new RuntimeException("Can not start in state " + getState());
    }
    public void stop(Car c) {
        throw new RuntimeException("Can not stop in state " + getState());
    }
    public abstract String getState();
}

class MoveState extends State {
    public final static MoveState INSTANCE = new MoveState();
    private MoveState() {
    }
    public void stop(Car c) {
        c.ChangeState(HoldState.INSTANCE);
    }
    public String getState() {
        return "moving";
    }
}

class HoldState extends State {
    public final static HoldState INSTANCE = new HoldState();
    private HoldState() {
    }
    public void start(Car c) {
        c.ChangeState(MoveState.INSTANCE);
    }
    public String getState() {
        return "holding";
    }
}
