状态模式

状态模式允许一个对象再其内部状态改变的时候改变其行为

 

状态模式的结构:


 

抽象状态角色:定义一个接口,用以封装环境对象的一个特定的状态所对应的行为

具体状态角色:每一个具体状态类都实现了环境的一个状态所对应的行为

环境角色:定义客户端所感兴趣的接口,并且保留一个具体状态类的实例,这个具体状态类的实例给出此环境对象的现有状态

 

首先我们抽象出状态,以及该状态下的行为,
interface State{
    public void shot();
}
然后实现具体状态,我们这里有三个,三种状态三种行为。
不正常
public class NonormalState implements State{
    public void shot(){
    System.out.println("
今天你投篮十中一");
}
}
正常:
public class NormalState implements State{
    public void shot(){
    System.out.println("
今天你投篮十中五");
}
}
超常:
public class SuperState implements State{
    public void shot(){
    System.out.println("
今天你投篮十中十");
}
}
这个时候我们来一个环境,一个运动员,正常情况下是正常状态
public class Player{
         private State state=new NormalState();
public void setState(State state){
      this.state=state;
}
      public void shot(){
            state.shot();//
这里我感觉是创建型模式的适配器模式,对象适配器。应该就是这样,
    }
}
测试这个例子
public class StateTest
{
   public static void main(String[] args){
Player player=new Player();
player.shot();//
正常下投篮
player.setState(new NonormalState());
player.shot();
不正常下投篮
player.setState(new SuperState());
player.shot();
超常下投篮
}
}

原文地址:https://www.cnblogs.com/jinzhengquan/p/1935900.html