状态模式的定义是允许一个对象通过改变它的状态来改变它的行为。状态模式中有以下几种角色上下文类:抽象状态类,用于记录状态、修改状态、调用行为等:所有类的父类,用来表示同一类型的状态,定义一个行为接口特定状态类:不同状态的具体实现下面是使用状态模式实现打印机的行为。上下文类公共类PrinterContext{私有PrinterState状态;publicPrinterContext(PrinterStatestate){this.state=state;}publicPrinterStategetState(){返回状态;}publicvoidsetState(PrinterStatestate){this.state=state;}publicvoidhandle(){state.handle(this);}}抽象状态类publicinterfacePrinterState{voidhandle(PrinterContextcontext);}具体状态类publicclassOccupyStateimplementsPrinterState{@Overridepublicvoidhandle(PrinterContextcontext){System.out.println("正在使用打印机....");尝试{Thread.sleep(2000);}catch(InterruptedExceptione){e.printStackTrace();}finally{System.out.println("打印结束,进入空闲模式");context.setState(newIdleState());}}}publicclassIdleStateimplementsPrinterState{@Overridepublicvoidhandle(PrinterContextcontext){System.out.println("打印机空闲....");}}测试类publicclassStateTest{@Testpublicvoidtest(){PrinterStateoccupiedState=newOccupyState();PrinterContextcontext=newPrinterContext(occupyState);context.handle();}}=====Result=====Printerisbeingused....打印完成后进入空闲模式。状态模式与策略模式非常相似。很容易看出两者之间的一些差异
