首页 > Java > java教程 > State

State

Mary-Kate Olsen
发布: 2024-09-22 22:15:32
原创
693 人浏览过

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);
}
登录后复制

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

登录后复制

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());
    }
}
登录后复制

output:

Player is in StartState
Start State
Player is in EndState
End State
登录后复制

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

以上是State的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板