10.2.2021 |

State Pattern

Description

The state pattern should deal with 2 major problems:

  • An object should change its behavior when its internal state changes. As an example, we have a player character that should play different animations. Depending on what is happening. Jump, Idle, Run, Attack...
  • State-specific behavior should be defined independently. That is, adding new states should not affect the behavior of existing states.
    • Not much happens in the Idle animation.
    • In the Jump animation, height-controlled frames -> additional calculations should be performed.

In a state, it can also be determined, for example, which state I can execute next.

  • from Idle I can go directly to Jump, Attack, Run
  • From Jump I can go directly to Run, Idle but not Attack.

UML

Code

interface State {
    String open(StateContext context);

    String close(StateContext context);
}

class OpenState implements State {
    @Override
    public String open(StateContext context) {
        return "Is Already Open, so cant open again";
    }

    @Override
    public String close(StateContext context) {
        context.state = new CloseState();
        return "Close";
    }
}

class CloseState implements State {
    @Override
    public String open(StateContext context) {
        context.state = new OpenState();
        return "Open";
    }

    @Override
    public String close(StateContext context) {
        return "Is Already Closed, so cant close again";
    }
}

class StateContext {
    State state = new OpenState();

    void open() {
        System.out.println(state.open(this));
    }

    void close() {
        System.out.println(state.close(this));
    }
}
Zur Übersicht

Mehr vom DevSquad...

Lucas Meurer

NestJS Logger Quiz

Sven Röttering

Facade