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 }
原文地址:https://www.cnblogs.com/BenWong/p/2813982.html