java 設計模式實例 - 狀態模式


狀態模式(State Pattern)是設計模式的一種,屬於行為模式。

  定義(源於Design Pattern):當一個對象的內在狀態改變時允許改變其行為,這個對象看起來像是改變了其類。 

  狀態模式主要解決的是當控制一個對象狀態的條件表達式過於復雜時的情況。把狀態的判斷邏輯轉移到表示不同狀態的一系列類中,可以把復雜的判斷邏輯簡化。 

  意圖:允許一個對象在其內部狀態改變時改變它的行為 

  適用場景: 

  1.一個對象的行為取決於它的狀態,並且它必須在運行時刻根據狀態改變它的行為。 

  2.一個操作中含有龐大的多分支結構,並且這些分支決定於對象的狀態。

 

實例

1, 接口 State.java

View Code
1 package com.my.code;
2 
3 public interface State {
4     void handle(StateMachine machine);
5 }

2, 具體狀態一開始, StartState.java

View Code
1 package com.my.code;
2 
3 public class StartState implements State {
4 
5     public void handle(StateMachine machine) {
6         System.out.println("Start to process...");
7         machine.setCurrentSate(new DraftState());
8     }
9 }

3, 具體狀態二草稿,DraftState.java

View Code
1 package com.my.code;
2 
3 public class DraftState implements State {
4 
5     public void handle(StateMachine machine) {
6         System.out.println("Draft...");
7         machine.setCurrentSate(new PublishState());
8     }
9 }

4, 具體狀態三發布,PublishState.java

View Code
 1 package com.my.code;
 2 
 3 public class PublishState implements State {
 4 
 5     public void handle(StateMachine machine) {
 6         System.out.println("Publish...");
 7         machine.setCurrentSate(new CompletedState());
 8 
 9     }
10 
11 }

5, 具體狀態四完成,CompletedState.java

View Code
1 package com.my.code;
2 
3 public class CompletedState implements State {
4 
5     public void handle(StateMachine machine) {
6         System.out.println("Completed");
7         machine.setCurrentSate(null);
8     }
9 }

6, 狀態容器 及客戶端調用, StateMachine.java

View Code
 1 package com.my.code;
 2 
 3 import java.io.IOException;
 4 
 5 public class StateMachine {
 6     private State currentSate;
 7 
 8     public State getCurrentSate() {
 9         return currentSate;
10     }
11 
12     public void setCurrentSate(State currentSate) {
13         this.currentSate = currentSate;
14     }
15     
16     public static void main(String[] args) throws IOException {
17         StateMachine machine = new StateMachine();
18         State start = new StartState();
19         machine.setCurrentSate(start);
20         while(machine.getCurrentSate() != null){
21             machine.getCurrentSate().handle(machine);
22         }
23         
24         System.out.println("press any key to exit:");
25         System.in.read();
26     }
27 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM