预计阅读时间: 9 分钟
当我们业务流程中有很多状态的时候,我们可以采用状态模式。
例如我们有一个业务需要新增-审核-发布,那么这里就有三种状态(新增状态、审核状态、发布状态)。
每种状态里面可能会有不同的分类状态,例如审核-审核通过、审核不通过等。
我按照这种情形设计了以下类图:
新增状态、审核状态、发布状态、Context分别实现State接口,把Context作为上下文处理State,当业务进行到不同状态时,setState不同状态,调用处理方法doAction。
CommonBean作为中间传递的数据结构运载数据到相应的状态类里面进行处理,那业务要是需要doAction有返回值,怎么办呢?
我又增加了一个doActionReturn函数处理需要返回值的业务。
包名和类引用需要自己定义,在此不提供
代码实现:
/** * Created by pengguangyu on 2016/3/30. */ State.class public interface State { public void doAction(CommonBean commonBean); public CommonBean doActionReturn(CommonBean commonBean); } NewState .class public class NewState implements State { private Types typeState; public NewState(){} public NewState(Types typeState){ this.typeState = typeState; } public void BeforeAction(){ System.out.println("BeforeAction...."); } public void NewAction(){ System.out.println("NewAction...."); } public void AfterAction(){ System.out.println("AfterAction...."); } @Override public void doAction(CommonBean commonBean) { switch (this.typeState){ case BeforeAction:BeforeAction();break; case NewAction:NewAction();break; case AfterAction:AfterAction();break; } } @Override public CommonBean doActionReturn(CommonBean commonBean) { System.out.println("New Return...."); return null; } public static enum Types{ BeforeAction,NewAction,AfterAction } } CheckState .class public class CheckState implements State { public CheckState(){} @Override public void doAction(CommonBean commonBean) { System.out.println("Check...."); } @Override public CommonBean doActionReturn(CommonBean commonBean) { System.out.println("Check Return...."); return null; } } SendState .class public class SendState implements State { public SendState(){} @Override public void doAction(CommonBean commonBean) { System.out.println("Send...."); } @Override public CommonBean doActionReturn(CommonBean commonBean) { System.out.println("Send Return...."); return null; } }
上下文类:
/** * Created by pengguangyu on 2016/3/30. */ public class StateContext implements State { private State state; public static class StateContextHelper{ public static final StateContext INSTANCE = new StateContext(); } public static StateContext getInstance(){ return StateContextHelper.INSTANCE; } public StateContext setStateWith(State state){ this.state = state; return this; } public void setState(State state){ this.state = state; } public State getState() { return state; } @Override public void doAction(CommonBean commonBean) { this.state.doAction(commonBean); } @Override public CommonBean doActionReturn(CommonBean commonBean) { this.state.doActionReturn(commonBean); return null; } }
通用Bean
public class CommonBean { }
学习慢慢来,鸡汤还是要有的。