Implement State pattern with enum

State pattern allow to choose the correct action related to the state of an object. The goal is to get rid of if/elseif and switch blocks.

You can replace constants which represents state by implementing the pattern as follows :

public class A {
    private int state = State.OPEN;

    class State {
        public static final int OPEN = 1;
        public static final int CLOSE = 2;
    }
}
public class A {
    private State state;

    interface State {}
    class OpenedState implements State {}
    class CloseState implements State {}
}

But now if you want to compare the state, you must use the instanceof operator.

You can do better with enum :

public class A {
    private State state;
    public A(State state) { this.state = state; }
    public State getState() { return state; }
    public void setState(State state) { this.state = state; }

    public void doSomething() { state.doSomething(); }

    public static void main(String[] argv) {
        A a = new A(State.CLOSE);
        a.doSomething();
        a.setState(State.OPEN);
        a.doSomething();
    }
    
    enum State {
        OPEN(new StateOpen()), CLOSE(new StateClose());
    
        private StateInterface stateInterface;

        private State(StateInterface stateInterface) { this.stateInterface = stateInterface; }
        
        public void doSomething() { stateInterface.doSomething(); }
    
        public static interface StateInterface { void doSomething(); }
        public static class StateOpen implements StateInterface {
            public void doSomething() { System.out.println("open"); }
        }
        public static class StateClose implements StateInterface {
            public void doSomething() { System.out.println("close"); }
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s