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
  • 相关阅读:
    F系列车牌识别设备
    金蝶云星空安装及卸载教程
    RG-RAC256高性能无线控制器
    关于IP网段划分
    Win10关闭自动更新的三种方法
    锐捷网络RG-S2528G-24P
    光纤信号的传输距离
    POE交换机
    光纤收发器
    大华工具管家 1.01.1官方版
  • 原文地址:https://www.cnblogs.com/XDJjy/p/3938209.html
Copyright © 2011-2022 走看看