代码如下:
import java.util.Scanner; public class Main { public static void main(String[] args) { @SuppressWarnings("resource") 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); } } } class BotContext { private State state = new DisconnectedState(); private boolean busy = false; // 定义工作线程时,记得在线程结束时将busy设置成false // private Thread work; public void setState(State state) { this.state = state; } public boolean isBusy() { return busy; } public void setBusy(boolean arg) { busy = arg; } public String chat(String input) { return state.reply(input, this); } } interface State { String init(); String reply(String input,BotContext bot); } class DisconnectedState implements State { @Override public String init() { return "Bye!"; } @Override public String reply(String input, BotContext bot) { if ("hello".equalsIgnoreCase(input)) { State nextState = new ConnectedState(); bot.setState(nextState); return nextState.init(); } else { return ""; } } } class ConnectedState implements State { @Override public String init() { return "Hello, I'm Bob."; } @Override public String reply(String input, BotContext bot) { if ("bye".equalsIgnoreCase(input)) { State nextState = new DisconnectedState(); bot.setState(nextState); return nextState.init(); } else if ("Go to work".equalsIgnoreCase(input)) { // 可在此以多线程方式开启任务,并将BotContext保存到Work中以便在线程结束时切换状态 // Thread t = new Work(bot); t.start(); bot.setWork(t); bot.setBusy(true); State nextState = new BusyState(); bot.setState(nextState); return nextState.init(); } else { if (input.endsWith("?")) { return "Yes. " + input.substring(0, input.length() - 1) + "!"; } if (input.endsWith(".")) { return input.substring(0, input.length() - 1) + "!"; } return input.substring(0, input.length() - 1) + "?"; } } } class BusyState implements State { @Override public String init() { return "Yes Sir. I'm working..."; } @Override public String reply(String input, BotContext bot) { if ("Stop".equalsIgnoreCase(input)) { // 可在此中断线程,强制切换回在线状态 // bot.getWork().interrupt(); bot.setBusy(false); bot.setState(new ConnectedState()); return "Ok, I have stopped working."; } else if (!bot.isBusy()) { // 工作正常结束时,可通过此分支切换回在线状态并回复消息 State nextState = new ConnectedState(); bot.setState(nextState); return nextState.reply(input, bot); } else { return "Sorry, I'm busy now!"; } } }
Sign in to make a reply
罗密欧与傅立页
代码如下: