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

 

转载: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();

}

}

posted on 2016-09-14 11:51  反光的小鱼儿  阅读(241)  评论(0编辑  收藏  举报