之前有一个需求,是学生答卷之后,根据不同的得分,进行不同的提分流程操作,当时写功能的时候,针对提分流程的操作,写了一大堆if……else操作,最近在思考代码美化的过程,突然发现此流程可以使用 状态模式 来代替,重新查了一下 设计模式-状态模式 的实现:
身为程序员,废话不多说,直接上例子,例子是写书的过程的例子:
写书分为多个过程:开始构造,草稿,发布,完成
通用接口:
public interface State {
void handle(StateMachine machine);
}
标示当前状态的类:
public class StateMachine {
private State currentSate;
public State getCurrentSate() {
return currentSate;
}
public void setCurrentSate(State currentSate) {
this.currentSate = currentSate;
}
}
开始构造的过程:
public class StartState implements State {
public void handle(StateMachine machine) {
System.out.println("Start to process...");
machine.setCurrentSate(new DraftState());
}
}
草稿过程:
public class DraftState implements State {
public void handle(StateMachine machine) {
System.out.println("Draft...");
machine.setCurrentSate(new PublishState());
}
}
发布过程:
public class PublishState implements State {
public void handle(StateMachine machine) {
System.out.println("Publish...");
machine.setCurrentSate(new CompletedState());
}
}
完成过程:
public class CompletedState implements State {
public void handle(StateMachine machine) {
System.out.println("Completed");
machine.setCurrentSate(null);
}
}
客户端Test:
public class Test{
public static void main(String[] args) throws IOException {
StateMachine machine = new StateMachine();
State start = new StartState();
machine.setCurrentSate(start);
while(machine.getCurrentSate() != null){
machine.getCurrentSate().handle(machine);
}
}
}
最后,个人觉得,状态模式的用处还是满广的,比如说开关灯的问题,设计一个通用的状态state,之后不同的两个过程,LightOn, LightOff 开灯之后把状态改为关状态,关灯之后把状态改为开状态,这样,可以循环调用方法,开关灯的功能就能循环实现;免除了每次都要写if……else方法,开关灯的功能,状态就少,如果状态多了,if……else的语句就会很多,而且不利于维护;
举个例子,如果是商场的会员卡操作,会员卡根据积分化为多种类别:普通,vip,白金,黄金……,不同类别的话,购买不同产品的折扣是不一样的··那么,这种需求如果使用状态模式的话,就很容易实现,不同的卡类型,只关注此卡的折扣就可,而且后续维护起来也很方便,增加新的卡类别,也不需要修改整个业务逻辑,只需要增加对应的类即可。