DEV Community

eidher
eidher

Posted on • Edited on

1

State Pattern

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

Alt Text

Participants

  • Context: defines the interface of interest to clients Maintains an instance of a ConcreteState subclass that defines the current state.
  • State: defines an interface for encapsulating the behavior associated with a particular state of the Context.
  • Concrete State: each subclass implements a behavior associated with a state of Context

Code

public class Main {

    public static void main(String[] args) {
        Context c = new Context(new ConcreteStateA());
        c.request();
        c.request();
        c.request();
        c.request();
    }
}

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

public class ConcreteStateA implements State {

    @Override
    public void handle(Context context) {
        context.setState(new ConcreteStateB());
    }
}

public class ConcreteStateB implements State {

    @Override
    public void handle(Context context) {
        context.setState(new ConcreteStateA());
    }
}

public class Context {

    private State state;

    public Context(State state) {
        setState(state);
    }

    public State getState() {
        return state;
    }

    public void setState(State state) {
        this.state = state;
        System.out.println("State: " + state.getClass().getSimpleName());
    }

    public void request() {
        state.handle(this);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

State: ConcreteStateA
State: ConcreteStateB
State: ConcreteStateA
State: ConcreteStateB
State: ConcreteStateA
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay