package command; import model.CrawlResult; import exception.CrawlerException; import view.CrawlerView; import java.util.List; public class RetryCommand implements Command { private final Command originalCommand; private final int maxRetries; private final CrawlerView view; public RetryCommand(Command originalCommand, int maxRetries, CrawlerView view) { this.originalCommand = originalCommand; this.maxRetries = maxRetries; this.view = view; } @Override public List execute() throws CrawlerException { CrawlerException lastException = null; for (int attempt = 1; attempt <= maxRetries; attempt++) { try { view.showMessage("执行命令: " + originalCommand.getName() + " (尝试 " + attempt + "/" + maxRetries + ")"); return originalCommand.execute(); } catch (CrawlerException e) { lastException = e; view.showError("命令执行失败: " + e.getMessage()); if (attempt < maxRetries) { view.showMessage("等待重试..."); try { Thread.sleep(1000 * attempt); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); break; } } } } view.showError("命令执行失败,已达到最大重试次数 " + maxRetries); throw lastException; } @Override public String getName() { return "Retry[" + originalCommand.getName() + "]"; } }