第五篇 驱动方法 第十五章 - 状态模式

 “水光潋滟晴方好,山色空蒙雨亦奇。”
  我们曾以西湖美景为例,介绍了若干对象协作完成其类全部功能的程序设计风格,从而引出了“对象多样性”的概念。
  其源码如下。

// 西湖
public class Xihu {

  private String state;

  public Xihu(String state) {
    this.state = state;
  }

  public void show() {
    if ("晴".equals(this.state)) {
      // 水光潋滟
    }
    if ("雨".equals(this.state)) {
      // 山色空蒙
    }
  }

}

  我们继续开拓思路。
  晴则水光潋滟,雨则山色空蒙,对象的行为与对象的状态紧密相连。更进一步说,对象的行为可以从属于它所处的状态。对象处于何种状态,就会有何种相应的行为,若对象的状态改变了,其行为也随之发生变化。
  以上正是状态模式的设计思路。
  状态模式把对象的行为封装在了相应的状态里,以状态的切换驱动方法的执行
  来看例子。

// 西湖
public class Xihu {

  private State state;// 当前状态

  // 设置状态
  public void setState(State state) {
    this.state = state;
    this.state.of(this);
  }

  // 默认状态
  {
    setState(State.SUNNY);
  }

  /* 将自身功能委托给状态对象 */

  // 水光
  public void showLake() {
    this.state.showLake();
  }

  // 山色
  public void showHill() {
    this.state.showHill();
  }

}

// 状态父类
public class State {

  public static final State SUNNY = new SunnyState();// 晴
  public static final State RAINY = new RainyState();// 雨

  protected Xihu obj;

  public void of(Xihu obj) {
    this.obj = obj;
  }

  // 水光
  public void showLake() {
    this.obj.setState(SUNNY);
    this.obj.showLake();
  }

  // 山色
  public void showHill() {
    this.obj.setState(RAINY);
    this.obj.showHill();
  }

}

// “晴”状态
public class SunnyState extends State {

  // 水光
  @Override
  public void showLake() {
    // 水光潋滟
  }

}

// “雨”状态
public class RainyState extends State {

  // 山色
  @Override
  public void showHill() {
    // 山色空蒙
  }

}

// 测试类
public class Test {

  public void test() {
    Xihu obj = new Xihu();
    obj.showLake();
    obj.showHill();
    obj.showLake();
  }

}

  一番设计后,“晴”“雨”两个状态的职责单一且明晰 ——“晴”状态只负责“水光”,雨”状态只负责“山色”。
  新增或移除某个状态时,不会影响其他状态的切换与相应的方法的执行,程序的基本结构相当稳定。
  状态模式适用于状态区分明显的事物或流程建模,它可以帮我们厘清状态之间的界限,把复杂的问题渐次分解。

posted on 2025-03-24 22:51  星辰河岳  阅读(23)  评论(0)    收藏  举报