熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

該如何實踐State模式

2022-06-13   來源: Java核心技術 

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());
    }
}
由兩個具體狀態類可知具體狀態之間的轉換由它們自身定義
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26679.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.