State设计模式定义:允许一个状态在改变其状态时,改变它的行为。我们将每
一种状态封装成一个单独的类,但所有的状态类需要有一个同一个规范(接口)
这样,运行时,根据传入的状态不同,表现不同的行为。
我们打篮球的时候运动员可以有正常状态,不正常状态,和超常状态,现在我们就
以我们打篮球时候投篮时候的状态来举例子,
首先我们抽象出状态,以及该状态下的行为,
interface State{
public void shot();
}
然后实现具体状态,我们这里有三个,三种状态三种行为。
不正常
public class AbnormalState 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(); 超常下投篮
}
}
使用状态模式的好处是每个状态被封装到一个独立的类中,这些类可以独立变
化,而主对象中没有繁琐的swich-case 语句,并且添加新的状态非常容易,只需
要从State 派生一个新类即可。