What is state design pattern?

State design pattern

The state pattern is one of the behavioral design patterns. The class behavior is changed based on its state. The State design pattern is used when an object changes its behavior based on its internal state.

Code example of state design pattern

    public interface State {
        public void processOrder(Context context);
    }

    public class StartOrder implements State {

        public void processOrder(Context context) {
            System.out.println("The order processing has started.");
            context.setState(this);
        }

        public String toString(){
            return "Start State";
        }
    }


    public class FinishedOrder implements State {

        public void processOrder(Context context) {
            System.out.println("The order processing is completed.");
            context.setState(this);
        }

        public String toString(){
            return "Finished State";
        }
    }


    public class Context {
        private State state;

        public Context(){
            state = null;
        }

        public void setState(State state){
            this.state = state;
        }

        public State getState(){
            return state;
        }
    }



    public class StatePattern {
        public static void main(String[] args) {

            Context context = new Context();
            
            var startOrder = new StartOrder();
            startOrder.processOrder(context);
            System.out.println(context.getState());

            var finishedOrder = new FinishedOrder();
            finishedOrder.processOrder(context);
            System.out.println(context.getState());
        }
    }
Reference:

Share