随笔分类
状态模式
State
行为型之一
通过改变对象的内部状态而改变对象的行为,这个对象表现得就像是修改了它的类一样
为什么会有状态模式呢?
先来看看一份代码
public class Meal {
private int time;
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public void getMeal(int time) {
if (time == 8)
System.out.println("吃早餐");
else if (time == 12)
System.out.println("吃午餐");
else if (time == 18)
System.out.println("吃晚餐");
else System.out.println("没到饭点");
}
}
这是很糟糕的设计对吧,当一个对象状态很多时,显然糟糕
怎么解决呢
看过我之前博客的人应该知道吧
没错,
就是抽离状态
public class Meal {
private int time;
private State state;
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public void getMeal() {
this.state = new BreakfastMeal(); //复位
this.state.getMeal(this);
}
}
public class BreakfastMeal implements State{
@Override
public void getMeal(Meal meal) { //有点像链表的传递
if (meal.getTime() == 8)
System.out.println("吃早餐");
else {
meal.setState(new LunchMeal());
meal.getState().getMeal(meal);
}
}
}
public class LunchMeal implements State{
@Override
public void getMeal(Meal meal) {
if (meal.getTime() == 12)
System.out.println("吃午餐");
else {
meal.setState(new DinnerMeal());
meal.getState().getMeal(meal);
}
}
}
public class DinnerMeal implements State{
@Override
public void getMeal(Meal meal) {
if (meal.getTime() == 18)
System.out.println("吃晚餐");
else {
meal.setState(new NonMeal());
meal.getState().getMeal(meal);
}
}
}
public class NonMeal implements State{
@Override
public void getMeal(Meal meal) {
System.out.println("还没到饭点");
}
}
/**
* 还没到饭点
* 吃早餐
* 吃午餐
*/
public class Client {
public static void main(String[] args) {
Meal meal = new Meal();
meal.setTime(19);
meal.getMeal();
meal.setTime(8);
meal.getMeal();
meal.setTime(12);
meal.getMeal();
}
}
应用场景
-
状态模式主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的情况.
把状态的判断逻辑转译到表现不同状态的一系列类中去,这样可以把复杂的判断逻辑简化