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.
50 lines
1.5 KiB
50 lines
1.5 KiB
package com.example.datacollect.command;
|
|
|
|
import com.example.datacollect.model.Article;
|
|
import com.example.datacollect.model.DataService;
|
|
import com.example.datacollect.view.ConsoleView;
|
|
import java.util.List;
|
|
|
|
public class ListCommand implements Command {
|
|
private final ConsoleView view;
|
|
private static final int DEFAULT_LIMIT=20;
|
|
public ListCommand(ConsoleView view) {
|
|
this.view = view;
|
|
}
|
|
|
|
@Override
|
|
public String getName() {
|
|
return "list";
|
|
}
|
|
|
|
@Override
|
|
public void execute(String[] args,DataService dataService) {
|
|
// 1. 解析参数:list <limit>
|
|
int limit = DEFAULT_LIMIT;
|
|
if (args.length > 1) {
|
|
try {
|
|
limit = Integer.parseInt(args[1]);
|
|
if (limit < 1) {
|
|
view.printError("数量必须大于 0");
|
|
return;
|
|
}
|
|
} catch (NumberFormatException e) {
|
|
view.printError("参数必须是数字");
|
|
return;
|
|
}
|
|
}
|
|
// 2. 获取数据
|
|
List<Article> allArticles = dataService.getAllArticles();
|
|
int totalSize = allArticles.size();
|
|
// 3. 处理分页/截取
|
|
List<Article> displayList;
|
|
if (totalSize <= limit) {
|
|
displayList = allArticles;
|
|
} else {
|
|
displayList = allArticles.subList(0, limit);
|
|
}
|
|
// 4. 调用视图显示(传递总数以便显示分页信息)
|
|
view.display(displayList, totalSize);
|
|
}
|
|
|
|
}
|
|
|