State 模式核心思想:不同狀態,不同行為,即每個狀態擁有相應的行為邏輯。
當系統頻繁出現 if-else if-else 進行狀態判斷切換時,應考慮 State 模式。不僅限於狀態,物件屬性不同導致行為差異(如資料庫記錄的 property 欄位標識特殊性質)同樣適用。
一般狀態判斷: 狀態值由外部變數決定,狀態間無關聯
if (which == 1) state = "hello";
else if (which == 2) state = "hi";
else if (which == 3) state = "bye";
開關切換狀態(State 模式適用): 狀態按固定或可變規則相互轉換,如旋轉開關
if (state.equals("bye")) state = "hello";
else if (state.equals("hello")) state = "hi";
else if (state.equals("hi")) state = "bye";
public class Context {
private Color state = null;
public void push() {
if (state == Color.red) state = Color.blue;
else if (state == Color.blue) state = Color.green;
else if (state == Color.black) state = Color.red;
else if (state == Color.green) state = Color.black;
new Sample(state).operate();
}
public void pull() {
// 反向切換邏輯
if (state == Color.green) state = Color.blue;
else if (state == Color.black) state = Color.green;
else if (state == Color.blue) state = Color.red;
else if (state == Color.red) state = Color.black;
new Sample2(state).operate();
}
}
此例中 push/pull 兩種動作導致狀態雙向切換,適合 State 模式優化。但若狀態行為極簡單(單純賦值),引入 State 反而增加子類複雜度,需權衡。
需兩類實體參與:
Context,負責狀態切換動作state.handlePush(context))