Design Pattern:
In State pattern a class behavior changes based on its state. This type of design pattern comes under behavior pattern. 模式:类的行为是根据自己的状态而改变的,属于行为模式
故事场景: //Curry一般都是上午运球,下午投篮 所以Curry的训练根据时间状态变化
public interface Time {
public void doAction(Player player);
}
public class Morning implements Time {
@Override
public void doAction(Player player) {
player.setTime(this);
}
}
public class Afternoon implements Time {
@Override
public void doAction(Player player) {
player.setTime(this);
}
}
Curry
public class Player {
private Time time;
public void play(){
if (time instanceof Morning){
System.out.println("上午运球");
}else if(time instanceof Afternoon){
System.out.println("下午投篮");
}else{
System.out.println("休息");
}
}
public Time getTime() {
return time;
}
public void setTime(Time time) {
this.time = time;
}
}
实验的开始
public class StateDemo {
public static void main(String[] args) {
Player curry = new Player();
Morning morning = new Morning();
morning.doAction(curry);
curry.play();
Afternoon afternoon = new Afternoon();
afternoon.doAction(curry);
curry.play();
}
}