You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
43 lines
1.3 KiB
43 lines
1.3 KiB
package com.cctv.news.controller;
|
|
|
|
import com.cctv.news.command.Command;
|
|
import com.cctv.news.view.OutputView;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
|
|
public class CommandController {
|
|
private final Map<String, Command> commands;
|
|
private final OutputView view;
|
|
|
|
public CommandController(OutputView view) {
|
|
this.view = view;
|
|
this.commands = new HashMap<>();
|
|
}
|
|
|
|
public void registerCommand(Command command) {
|
|
commands.put(command.getName(), command);
|
|
}
|
|
|
|
public void executeCommand(String input) {
|
|
if (input == null || input.trim().isEmpty()) {
|
|
view.showError("命令不能为空");
|
|
return;
|
|
}
|
|
|
|
String[] parts = input.trim().split("\\s+");
|
|
String commandName = parts[0];
|
|
String[] args = parts.length > 1 ? java.util.Arrays.copyOfRange(parts, 1, parts.length) : new String[0];
|
|
|
|
Command command = commands.get(commandName);
|
|
if (command != null) {
|
|
try {
|
|
command.execute(args);
|
|
} catch (Exception e) {
|
|
view.showError("执行命令时出错: " + e.getMessage());
|
|
}
|
|
} else {
|
|
view.showError("未知命令: " + commandName + ",输入 help 查看可用命令");
|
|
}
|
|
}
|
|
}
|
|
|