Home > Java > javaTutorial > State

State

Mary-Kate Olsen
Release: 2024-09-22 22:15:32
Original
693 people have browsed it

State

The State is one of the Behavioral design patterns, In this the behavior of a class changes based on its state.

Key concepts:
Context: Class/object whose behavior changes based on state
State: abstract state
Concrete State: representing various states, which changes the behavior of the Context class.

Let's understand this with an example:

State.java

public interface State {
    public void doAction(Context context);
}
Copy after login

Concrete Implementation of State

public class StartState implements State {
    private Context context;
    public StartState(){}
    @Override
    public void doAction(Context context){
        this.context = context;
        this.context.setState(this);
        System.out.println("Player is in StartState");
    }

    public String toString(){
        return "Start State";
    }
}

public class EndState implements State {
    private Context context;
    public EndState(){}
    @Override
    public void doAction(Context context){
        this.context = context;
        this.context.setState(this);
        System.out.println("Player is in EndState");
    }

    public String toString(){
        return "End State";
    } 
}

Copy after login

Main

public class Main {
    public static void main(String args[]){
        Context context = new Context();
        State state = new StartState();
        state.doAction(context);
        //current state
        System.out.println(context.getState().toString());

        State state2 = new EndState();
        state2.doAction(context);
        //new State
        System.out.println(context.getState().toString());
    }
}
Copy after login

output:

Player is in StartState
Start State
Player is in EndState
End State
Copy after login

note: The above code follows ISP, LSP, SRP, OCP of solid principles

The above is the detailed content of State. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template