State模式将对象行为的变化封装成具有统一接口的状态它与Strategy模式的区别在于任何状态的改变都是定义好的即改变行为的动作由自己来做 <![if !vml]> <![endif]> 下面是自动门的状态图它描述了开与关两个状态之间的变化条件 <![if !vml]> <![endif]> 抽象状态DoorState提供open()和close()两个方法 package comzjdoorstate;
public interface DoorState { void open();
void close(); } Context为AutoDoor它关联一个DoorState state package comzjdoorstate;
public class AutoDoor { private DoorState state; private DoorState open = new Open(this); private DoorState close = new Close(this);
public AutoDoor() { thisstate = open; }
public void setSate(DoorState state) { thisstate = state; }
public DoorState getOpenState() { return open; }
public DoorState getCloseState() { return close; }
public void open() { stateopen(); }
public void close() { stateclose(); } } ConcreteState有两个 状态Open package comzjdoorstate;
public class Open implements DoorState { private AutoDoor door;
public Open(AutoDoor door) { thisdoor = door; }
public void close() { Systemoutprintln(OK Door closed); doorsetSate(doorgetCloseState()); }
public void open() { Systemoutprintln(Door already opened); } } 状态Close package comzjdoorstate;
public class Close implements DoorState { private AutoDoor door;
public Close(AutoDoor door) { thisdoor = door; }
public void close() { Systemoutprintln(Door already closed); }
public void open() { Systemoutprintln(OK Door opened); doorsetSate(doorgetOpenState()); } } 由两个具体状态类可知具体状态之间的转换由它们自身定义 |