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.
57 lines
1.8 KiB
57 lines
1.8 KiB
package com.example.datacollect.w9.controller;
|
|
|
|
import com.example.datacollect.w9.command.*;
|
|
import com.example.datacollect.w9.model.Article;
|
|
import com.example.datacollect.w9.view.ConsoleView;
|
|
import java.util.ArrayList;
|
|
import java.util.HashMap;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
|
|
public class CrawlerController {
|
|
private final Map<String, Command> commands = new HashMap<>();
|
|
private final Map<String, String> aliases = new HashMap<>();
|
|
private final ConsoleView view;
|
|
private final List<Article> articles;
|
|
private final List<String> history = new ArrayList<>();
|
|
|
|
public CrawlerController(ConsoleView view, List<Article> articles) {
|
|
this.view = view;
|
|
this.articles = articles;
|
|
register(new HelpCommand(view));
|
|
register(new ListCommand(view));
|
|
register(new CrawlCommand(view, articles));
|
|
register(new ExitCommand(view));
|
|
register(new HistoryCommand(view, history));
|
|
registerAlias("c", "crawl"); // 别名 c = crawl
|
|
}
|
|
|
|
private void register(Command command) {
|
|
commands.put(command.getName(), command);
|
|
}
|
|
|
|
private void registerAlias(String alias, String commandName) {
|
|
aliases.put(alias, commandName);
|
|
}
|
|
|
|
public void handle(String input) {
|
|
String text = input == null ? "" : input.trim();
|
|
if (text.isEmpty()) return;
|
|
|
|
history.add(text);
|
|
|
|
String[] args = text.split("\\s+");
|
|
String cmdName = args[0].toLowerCase();
|
|
|
|
if (aliases.containsKey(cmdName)) {
|
|
cmdName = aliases.get(cmdName);
|
|
}
|
|
|
|
Command command = commands.get(cmdName);
|
|
if (command == null) {
|
|
view.printError("Unknown command: " + cmdName);
|
|
return;
|
|
}
|
|
command.execute(args, articles);
|
|
}
|
|
}
|
|
|