路一步步走>> 設計模式二十:State-狀態
阿新 • • 發佈:2018-12-08
package com.test.DPs.XingWei.State; /** * 行為型:State-狀態 外觀:作用面為 物件 * * 用途:允許一個物件在其內部狀態改變時改變它的行為。物件看起來改變它的類。 * * 理解:通過狀態改變(觸發、開關)行為;(狀態可主動) * 該行為影響某些操作。 */ class State{ private String value; public String getValue(){ return value; } public void setValue(String value){ this.value = value; } public void method1(){ System.out.println("execute the first opt!"); } public void method2(){ System.out.println("execute the second opt!"); } } class Context{ private State state; public Context(State state){ this.state = state; } public State getState(){ return state; } public void setState(State state){ this.state = state; } public void method(){ if(state.getValue().equals("state1")) { state.method1(); } else if (state.getValue().equals("state2")) { state.method2(); } } } class Test { public static void main(String[] args) { State state = new State(); Context context = new Context(state); state.setValue("state1"); //設定第一種狀態, 內部發生變化 context.method(); state.setValue("state2"); //設定第二種狀態 context.method(); } }