package com.example.datacollect.command; import com.example.datacollect.model.Article; import com.example.datacollect.model.DataService; import com.example.datacollect.service.HistoryService; import com.example.datacollect.view.ConsoleView; import java.util.List; public class HistoryCommand implements Command { private final ConsoleView view; private final HistoryService historyService; public HistoryCommand(ConsoleView view, HistoryService historyService) { this.view = view; this.historyService = historyService; } @Override public String getName() { return "history"; } @Override public void execute(String[] args, DataService dataService) { // 参数解析:history 或 history if (args.length == 1) { // 显示全部 List allHistory = historyService.getHistory(); view.displayHistory(allHistory); return; } String param = args[1].toLowerCase(); if (param.equals("clear")) { historyService.clear(); view.printSuccess("历史命令已清空。"); return; } try { int limit = Integer.parseInt(param); List allHistory = historyService.getHistory(); if (limit <= 0) { view.printError("数量必须大于 0"); return; } // 显示最近 N 条 int start = Math.max(0, allHistory.size() - limit); List recentHistory = allHistory.subList(start, allHistory.size()); view.printInfo("最近 " + limit + " 条命令:"); System.out.println("--------------------------------------------------"); for (int i = 0; i < recentHistory.size(); i++) { System.out.println((recentHistory.size() - i) + ". " + recentHistory.get(i)); } System.out.println("--------------------------------------------------"); } catch (NumberFormatException e) { view.printError("参数必须是数字或 'clear'"); } } }