zoukankan      html  css  js  c++  java
  • 设计模式(java)--状态模式

    状态模式(State Pattern)是设计模式的一种,属于行为模式。

      定义(源于Design Pattern):当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。 

      状态模式主要解决的是当控制一个对象状态的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类中,可以把复杂的判断逻辑简化。 

      意图:允许一个对象在其内部状态改变时改变它的行为 

      适用场景: 

      1.一个对象的行为取决于它的状态,并且它必须在运行时刻根据状态改变它的行为。 

      2.一个操作中含有庞大的多分支结构,并且这些分支决定于对象的状态。

    实例:

    package tm;
    
    import java.io.IOException;
    //1, 接口 State.java
    interface State {
         void handle(Client machine);
     }
    //2, 具体状态一开始, StartState.java
    class StartState implements State {
    
        public void handle(Client machine) {
            System.out.println("Start to process...");
            machine.setCurrentSate(new DraftState());
        }
    }
    //3, 具体状态二草稿,DraftState.java
    class DraftState implements State {
    
        public void handle(Client machine) {
            System.out.println("Draft...");
            machine.setCurrentSate(new PublishState());
        }
    }
    //4, 具体状态三发布,PublishState.java
    class PublishState implements State {
    
        public void handle(Client machine) {
            System.out.println("Publish...");
            machine.setCurrentSate(new CompletedState());
    
        }
    }
    //5, 具体状态四完成,CompletedState.java
    class CompletedState implements State {
    
        public void handle(Client machine) {
            System.out.println("Completed");
            machine.setCurrentSate(null);
        }
    }
    
    //6, 状态容器 及客户端调用, StateMachine.java
    public class Client {
        private State currentSate;
    
        public State getCurrentSate() {
            return currentSate;
        }
    
        public void setCurrentSate(State currentSate) {
            this.currentSate = currentSate;
        }
        
        public static void main(String[] args) throws IOException {
            Client machine = new Client();
            State start = new StartState();
            machine.setCurrentSate(start);
            while(machine.getCurrentSate() != null){
                machine.getCurrentSate().handle(machine);
            }
            
            System.out.println("press any key to exit:");
            System.in.read();
        }
    } 
    View Code
  • 相关阅读:
    Educational Codeforces Round 51 (Rated for Div. 2)
    Kruskal重构树入门
    编译原理词法分析
    java.lang.String内部结构的变化
    android 世界各国英文简写代码 资源文件
    openCV python 安装
    解读30个提高Web程序执行效率的好经验
    从认知盈余说起,也谈分享精神
    STL set multiset map multimap unordered_set unordered_map example
    [置顶] 【Git入门之一】Git是神马?
  • 原文地址:https://www.cnblogs.com/XDJjy/p/3938209.html
Copyright © 2011-2022 走看看