电脑故障

位置:IT落伍者 >> 电脑故障 >> 浏览文章

该如何实践State模式


发布日期:2019/1/23
 

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());

}

}

由两个具体状态类可知具体状态之间的转换由它们自身定义

上一篇:黑马程序员之接口(interface)

下一篇:避免创建重复对象