Java 實現狀態(State)模式

來源:互聯網
上載者:User

標籤:string   tracking   one   test   text   client   pop   表單   name   

/** * @author stone */public class WindowState {private String stateValue;public WindowState(String stateValue) {this.stateValue = stateValue;}public String getStateValue() {return stateValue;}public void setStateValue(String stateValue) {this.stateValue = stateValue;}public void handle() {/* * 依據不同狀態做不同操作, 再切換狀態 */if ("表單".equals(stateValue)) {switchWindow();this.stateValue = "全屏";} else if ("全屏".equals(stateValue)) {switchFullscreen();this.stateValue = "表單";}}private void switchWindow() {System.out.println("切換為表單狀態");}private void switchFullscreen() {System.out.println("切換為全屏狀態");}}

/** * 狀態的使用 * @author stone * */public class WindowContext {private WindowState state;public WindowContext(WindowState state) {this.state  = state;}public WindowState getState() {return state;}public void setState(WindowState state) {this.state = state;}public void switchState() {this.state.handle();}}

/* * 狀態(State)模式 行為型模式 * 既改變對象的狀態,又改變對象的行為 * 依據狀態,改變行為 */public class Test {public static void main(String[] args) {/* * 本例的 狀態值僅僅有兩個,由狀態類自身控制 * 也能夠把狀態值的控制,交由client來設定 */WindowContext context = new WindowContext(new WindowState("表單"));context.switchState();context.switchState();context.switchState();context.switchState();}}

列印

切換為表單狀態切換為全屏狀態切換為表單狀態切換為全屏狀態




Java 實現狀態(State)模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.