State模式将对象行为的变化封装成具有统一接口的状态,它与Strategy模式的区别在于任何状态的改变都是定义好的,即“改变行为”的动作由自己来做。
下面是自动门的状态图,它描述了“开”与“关”两个状态之间的变化条件。
feedom.net
抽象状态DoorState提供open()和close()两个方法,
package com.zj.doorstate;
public interface DoorState {
void open();
void close();
}
Context为AutoDoor,它关联一个DoorState state。
package com.zj.doorstate;
public class AutoDoor {
private DoorState state;
private DoorState open = new Open(this);
private DoorState close = new Close(this);
public AutoDoor() {
this.state = open;
}
public void setSate(DoorState state) {
this.state = state;
}
public DoorState getOpenState() {
return open;
}
public DoorState getCloseState() {
return close;
}
public void open() {
state.open();
}
public void close() {
state.close();
}
}
ConcreteState有两个。
状态Open
package com.zj.doorstate;
public class Open implements DoorState {
private AutoDoor door;
public Open(AutoDoor door) {
this.door = door;
}
public void close() {
System.out.println("O.K. Door closed.");
door.setSate(door.getCloseState());
}
public void open() {
System.out.println("Door already opened.");
}
}
状态Close
package com.zj.doorstate;
public class Close implements DoorState {
private AutoDoor door;
public Close(AutoDoor door) {
this.door = door;
}
public void close() {
System.out.println("Door already closed.");
}
public void open() {
System.out.println("O.K. Door opened.");
door.setSate(door.getOpenState());
}
}
由两个具体状态类可知,具体状态之间的转换由它们自身定义。
【转自】
阅读(471) | 评论(0) | 转发(0) |