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));
    }
}

Wir freuen uns Sie kennen zu lernen

Hat Sie unser Angebot überzeugt? Dann freuen wir uns, Sie kennen zu lernen. Kontaktieren Sie uns gerne für ein unverbindliches Erstgespräch.

newcubator GmbH
Freie-Vogel-Straße 369
44269 Dortmund
dortmund@newcubator.com
+49 231/586 873 80
newcubator GmbH
Bödekerstraße 22
30161 Hannover
hannover@newcubator.com
+49 511/957 313 00