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.

96 lines
2.5 KiB

package com.example.datacollect.command;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* 命令历史记录管理器
* 用于记录用户输入的所有命令,并提供查看历史的功能
*/
public class HistoryCommand implements Command {
private List<String> commandHistory;
public HistoryCommand() {
this.commandHistory = new ArrayList<>();
}
/**
* 添加命令到历史记录
* @param command 用户输入的命令
*/
public void addCommand(String command) {
if (command != null && !command.trim().isEmpty()) {
commandHistory.add(command);
}
}
/**
* 打印所有历史命令
*/
public void printHistory() {
if (commandHistory.isEmpty()) {
System.out.println("暂无命令历史记录");
return;
}
System.out.println("===== 命令历史记录 =====");
for (int i = 0; i < commandHistory.size(); i++) {
System.out.println((i + 1) + ". " + commandHistory.get(i));
}
System.out.println("=======================");
}
/**
* 获取命令历史列表
* @return 命令历史列表的副本
*/
public List<String> getCommandHistory() {
return new ArrayList<>(commandHistory);
}
/**
* 清空历史记录
*/
public void clearHistory() {
commandHistory.clear();
}
@Override
public String getName() {
return "history";
}
@Override
public void execute(String[] args, List<Article> articles) {
printHistory();
}
/**
* 简单交互测试主方法
*/
public static void main(String[] args) {
HistoryCommand historyCommand = new HistoryCommand();
Scanner scanner = new Scanner(System.in);
System.out.println("===== 命令历史测试 =====");
System.out.println("输入命令(输入 exit 退出,输入 history 查看历史):");
while (true) {
System.out.print("\n> ");
String input = scanner.nextLine().trim();
if ("exit".equalsIgnoreCase(input)) {
System.out.println("退出程序");
break;
} else if ("history".equalsIgnoreCase(input)) {
historyCommand.printHistory();
} else {
historyCommand.addCommand(input);
System.out.println("命令已记录: " + input);
}
}
scanner.close();
}
}