该如何实践State模式

State模式将对象行为的变化封装成具有统一接口的状态,它与Strategy模式的区别在于任何状态的改变都是定义好的,即“改变行为”的动作由自己来做。

<!--[if !vml]-->          <!--[endif]-->

下面是自动门的状态图,它描述了“开”与“关”两个状态之间的变化条件。

         <!--[if !vml]-->         <!--[endif]-->

抽象状态DoorState提供open()close()两个方法,

package com.zj.doorstate;

 

publicinterface DoorState {

    void open();

 

    void close();

}

ContextAutoDoor它关联一个DoorState state

package com.zj.doorstate;

 

publicclass AutoDoor {

    private DoorState state;

    private DoorState open = new Open(this);

    private DoorState close = new Close(this);

 

    public AutoDoor() {

       this.state = open;

    }

 

    publicvoid setSate(DoorState state) {

       this.state = state;

    }

 

    public DoorState getOpenState() {

       returnopen;

    }

 

    public DoorState getCloseState() {

       returnclose;

    }

 

    publicvoid open() {

       state.open();

    }

 

    publicvoid close() {

       state.close();

    }

}

ConcreteState有两个。

     状态Open

package com.zj.doorstate;

 

publicclass Open implements DoorState {

    private AutoDoor door;

 

    public Open(AutoDoor door) {

       this.door = door;

    }

 

    publicvoid close() {

       System.out.println("O.K. Door closed.");

       door.setSate(door.getCloseState());

    }

 

    publicvoid open() {

       System.out.println("Door already opened.");

    }

}

状态Close

package com.zj.doorstate;

 

publicclass Close implements DoorState {

    private AutoDoor door;

 

    public Close(AutoDoor door) {

       this.door = door;

    }

 

    publicvoid close() {

       System.out.println("Door already closed.");

    }

 

    publicvoid open() {

       System.out.println("O.K. Door opened.");

       door.setSate(door.getOpenState());

    }

}

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

以上是 该如何实践State模式 的全部内容, 来源链接: utcz.com/p/205695.html

回到顶部