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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

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