设计模式(二十二)——状态模式
当对象有多个状态,而且以后可能会增加状态的时候可以用状态模式。
应用场景
人在不同状态下有不同的心率,当前有SLEEP和STUDY两个状态
可以使用if else或者switch判断每一个状态
public class People {
private String Name;
private int age;
public enum peopleState {SLEEP,STUDY};
private peopleState state;
//set get
public People(String name, int age, peopleState state) {
Name = name;
this.age = age;
this.state = state;
}
public void PeopleState(peopleState state){
switch(state){
case SLEEP:
System.out.println("睡觉状态,心跳50-70");
break;
case STUDY:
System.out.println("学习状态,心跳60-100");
break;
}
}
}
现在新增一个状态,RUN,如果在以前的代码上进行更改,就不符合开闭原则了
可以使用状态模式:把不同状态的动作抽离出来,然后不同的状态去实现这个接口,这样以后如果有新的状态,就不会去修改原来的代码。
public interface PeopleState {
public void peopleState(People.peopleState state);
}
public class SleepPeopleState implements PeopleState{
public void peopleState(People.peopleState state) {
System.out.println("睡觉状态,心跳50-70");
}
}
public class StudyPeopleState implements PeopleState{
public void peopleState(People.peopleState state) {
System.out.println("学习状态,心跳60-100");
}
}