状态模式指给对象定义不同的状态,并为不同的状态定义不通的行为,在对象的状态发生变换时自动切换状态行为。
状态模式把受环境改变的对象行为包装在不同的对象里,用于让一个对象在其内部状态改变时,行为也随之改变。
(1)定义抽象状态
public abstract class AbstractState{ public abstract void action(Context context); }
(2)定义状态
public class HolidayState extends AbstractState{ private final static Log logger = LogFactory.getLog(this.getClass()); @Override public void action(Context context) { logger.info("state change to holiday state"); } } public class WorkState extends AbstractState{ private final static Log logger = LogFactory.getLog(this.getClass()); @Override public void action(Context context) { logger.info("state change to work state"); } }
(3)定义上下文用于存储状态和执行不同状态下的行为
public class Context{ private AbstractState state; public Context(AbstractState state){ this.state = state; } public void setState(AbstractState state) { this.state = state; } public AbstractState getState() { return state; } public void action(){ this.state.action(this); } }
(4)使用状态模式
public static void main(String[] args){ Context context = new Context(new WorkState()); context.action(); context.setState(new HolidayState()); context.action(); }