设计模式中,状态模式 (State Pattern) 的概念详解及示例说明。

状态模式 (State Pattern) 详解及示例


一、状态模式的概念

状态模式(State Pattern):允许对象在内部状态改变时,改变它的行为。对象看起来就像修改了它的类一样。

通俗点说:

  • 传统写法:对象用一个变量保存状态,然后一堆 if-else 判断逻辑,麻烦又难维护。
  • 状态模式:把不同状态的行为拆分到不同的类里,减少复杂的 if-else。

二、作用

  • 状态逻辑 封装到独立的类中,使代码更清晰。
  • 当增加新状态时,只需新增一个状态类,而不用修改原有代码,符合 开闭原则

三、特点

  1. 面向对象的封装:每个状态对应一个类,清晰表达状态逻辑。
  2. 易扩展:添加状态时不影响已有代码,只需新增类。
  3. 解耦:状态切换逻辑和状态本身的逻辑分开,便于维护。

四、练习:新增 BusyState

需求:

  • 忙碌状态 下,机器人不会认真聊天,而是统一回复 "I'm busy now, please try later."

五、完整代码示例

import java.util.Scanner;

// 状态接口
interface State {
    String init();
    String reply(String input);
}

// 离线状态
class DisconnectedState implements State {
    public String init() {
        return "Bye!";
    }
    public String reply(String input) {
        return ""; // 离线状态不回复
    }
}

// 已连接状态
class ConnectedState implements State {
    public String init() {
        return "Hello, I'm Bob.";
    }
    public String reply(String input) {
        if (input.endsWith("?")) {
            return "Yes. " + input.substring(0, input.length() - 1) + "!";
        }
        if (input.endsWith(".")) {
            return input.substring(0, input.length() - 1) + "!";
        }
        return input + "?";
    }
}

// 忙碌状态
class BusyState implements State {
    public String init() {
        return "I'm busy now.";
    }
    public String reply(String input) {
        return "I'm busy now, please try later.";
    }
}

// 上下文:机器人
class BotContext {
    private State state = new DisconnectedState(); // 初始状态

    public String chat(String input) {
        if ("hello".equalsIgnoreCase(input)) {
            state = new ConnectedState();
            return state.init();
        } else if ("bye".equalsIgnoreCase(input)) {
            state = new DisconnectedState();
            return state.init();
        } else if ("busy".equalsIgnoreCase(input)) {
            state = new BusyState();
            return state.init();
        }
        return state.reply(input);
    }
}

// 主程序
public class StatePatternDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        BotContext bot = new BotContext();
        for (;;) { // 无限循环
            System.out.print("> ");
            String input = scanner.nextLine();
            String output = bot.chat(input);
            System.out.println(output.isEmpty() ? "(no reply)" : "< " + output);
        }
    }
}

六、运行示例

> hello
< Hello, I'm Bob.
> Nice to meet you.
< Nice to meet you!
> busy
< I'm busy now.
> how are you?
< I'm busy now, please try later.
> bye
< Bye!

特点:带有 Disconnected / Connected / Busy 三种状态的聊天机器人,状态切换灵活。


小知识点

  • for (;;):无限循环,等价于 while(true)
  • private State state = new DisconnectedState();:设置状态机初始状态为离线。
posted @ 2025-09-09 15:12  AlphaGeek  阅读(37)  评论(0)    收藏  举报