Sobes.tech
Junior — Middle

How to implement the execution of different functions of methods within a class depending on the current state or mode of the class?

sobes.tech AI

Answer from AI

To implement different behavior variants of class methods depending on the current state or mode of operation, the "State" pattern is often used.

The idea is that the class has an internal state represented by separate objects implementing a common interface. The method call is delegated to the current state, which determines the specific behavior.

Example in Java:

interface State {
    void handle();
}

class StateA implements State {
    public void handle() {
        System.out.println("Behavior for state A");
    }
}

class StateB implements State {
    public void handle() {
        System.out.println("Behavior for state B");
    }
}

class Context {
    private State state;

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

    public void request() {
        state.handle();
    }
}

// Usage
Context context = new Context();
context.setState(new StateA());
context.request(); // Behavior for state A
context.setState(new StateB());
context.request(); // Behavior for state B

This way, you can change the behavior of methods without many conditional operators inside the class.

How to implement the execution of different functions… - sobes.tech