23 Sep 2014

Java设计模式:状态模式

注:本文为译文,原文出处java-design-patterns-in-stories

状态模式主要用于在运行时改变状态.

状态模式故事

人们生活在不同的经济条件下. 他们或许富有或许贫穷. 这两种状态 - 富有与贫穷 - 可以随时间相互转换. 例子背后的启示: 人们通常在贫穷时候工作的更加努力, 而富有时则更乐于享乐. 他们的行为依赖于他们的生活状态. 这个状态可以基于他们的行为被改变, 不然, 这个社会就不公平了.

状态模式类图

下面是类图. 你可以拿策略模式来进行比较, 以便能更好的理解两者的不同.

state-pattern-class-diagram

状态模式Java代码

下面的Java代码体现了状态模式是如何进行工作的.

状态类.

package com.programcreek.designpatterns.state;

interface State {
  public void saySomething(StateContext sc);
}

class Rich implements State{
  @Override
  public void saySomething(StateContext sc) {
    System.out.println("I'm rick currently, and play a lot.");
    sc.changeState(new Poor());
  }
}

class Poor implements State{
  @Override
  public void saySomething(StateContext sc) {
    System.out.println("I'm poor currently, and spend much time working.");
    sc.changeState(new Rich());
  }
}

状态上下文类.

package com.programcreek.designpatterns.state;

public class StateContext {
  private State currentState;

  public StateContext(){
    currentState = new Poor();
  }

  public void changeState(State newState){
    this.currentState = newState;
  }

  public void saySomething(){
    this.currentState.saySomething(this);
  }
}

测试类.

import com.programcreek.designpatterns.*;

public class Main {
  public static void main(String args[]){
    StateContext sc = new StateContext();
    sc.saySomething();
    sc.saySomething();
    sc.saySomething();
    sc.saySomething();
  }
}

输出结果:

I'm poor currently, and spend much time working.
I'm rick currently, and play a lot.
I'm poor currently, and spend much time working.
I'm rick currently, and play a lot.

Tags:
0 comments