设计模式13:状态模式

状态模式(State DP)允许对象在内部状态改变时改变行为,就好像换了一个类一样(原文:Allow an object to alter its behavior when its internal state changes. The object will appear to change its class)。
说起状态模式,就不得不提策略模式。两者都是在运行时可以改变行为,不同的是,策略模式是用户自己临时选择,而状态模式是用户之前定义好状态的转换,运行时根据既定的状态机来执行转换。当然,如果非得手动控制状态,那这两个模式确实很接近。

代码:
State接口:

/**
 * 
 * State interface.
 * 
 */
public interface State {

  void onEnterState();

  void observe();

}

猛犸:

/**
 * 
 * Mammoth has internal state that defines its behavior.
 * 
 */
public class Mammoth {

  private State state;

  public Mammoth() {
    state = new PeacefulState(this);
  }

  /**
   * Makes time pass for the mammoth
   */
  public void timePasses() {
    if (state.getClass().equals(PeacefulState.class)) {
      changeStateTo(new AngryState(this));
    } else {
      changeStateTo(new PeacefulState(this));
    }
  }

  private void changeStateTo(State newState) {
    this.state = newState;
    this.state.onEnterState();
  }

  @Override
  public String toString() {
    return "The mammoth";
  }

  public void observe() {
    this.state.observe();
  }
}

愤怒模式:

/**
 * 
 * Angry state.
 *
 */
public class AngryState implements State {

  private static final Logger LOGGER = LoggerFactory.getLogger(AngryState.class);

  private Mammoth mammoth;

  public AngryState(Mammoth mammoth) {
    this.mammoth = mammoth;
  }

  @Override
  public void observe() {
    LOGGER.info("{} is furious!", mammoth);
  }

  @Override
  public void onEnterState() {
    LOGGER.info("{} gets angry!", mammoth);
  }

}

平静模式:

/**
 * 
 * Peaceful state.
 *
 */
public class PeacefulState implements State {

  private static final Logger LOGGER = LoggerFactory.getLogger(PeacefulState.class);

  private Mammoth mammoth;

  public PeacefulState(Mammoth mammoth) {
    this.mammoth = mammoth;
  }

  @Override
  public void observe() {
    LOGGER.info("{} is calm and peaceful.", mammoth);
  }

  @Override
  public void onEnterState() {
    LOGGER.info("{} calms down.", mammoth);
  }

}

测试:

public static void main(String[] args) {

    Mammoth mammoth = new Mammoth();
    mammoth.observe();
    mammoth.timePasses();
    mammoth.observe();
    mammoth.timePasses();
    mammoth.observe();

  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容