zoukankan      html  css  js  c++  java
  • 状态模式

    定义:允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它的类。

    转载:http://www.cnblogs.com/BenWong/archive/2012/12/12/2813982.html

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

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

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

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

      适用场景: 

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

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

    实例

    public interface State {

        void handle(StateMachine machine);

    }

     

    状态1

    public class StartState implements State {

     

        public void handle(StateMachine machine) {

            System.out.println("Start to process...");

            machine.setCurrentSate(new DraftState());

        }

    }

     

    状态2

    public class DraftState implements State {

     

        public void handle(StateMachine machine) {

            System.out.println("Draft...");

            machine.setCurrentSate(new PublishState());

        }

    }

     

    状态3

    public class PublishState implements State {

     

        public void handle(StateMachine machine) {

            System.out.println("Publish...");

            machine.setCurrentSate(new CompletedState());

     

        }

     

    }

     

    状态4

    public class CompletedState implements State {

     

        public void handle(StateMachine machine) {

            System.out.println("Completed");

            machine.setCurrentSate(null);

        }

    }

     

    容器调用

    public class StateMachine {

    private State currentSate;

     

    public State getCurrentSate() {

    return currentSate;

    }

     

    public void setCurrentSate(State currentSate) {

    this.currentSate = currentSate;

    }

     

    public static void main(String[] args) throws IOException {

    StateMachine machine = new StateMachine();

    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();

    }

    }

  • 相关阅读:
    [Next] 六.next的优化
    [Next] 五.next自定义内容
    Mac解决端口占用
    [Next] 四.在next中引入redux
    [Next] 服务端渲染知识补充
    [Next] 三.next自定义服务器和路由
    哪些使用UDP、TCP、IP协议
    IDEA配置git
    ssm整合配置
    git传输远程仓库
  • 原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/5871341.html
Copyright © 2011-2022 走看看