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.
49 lines
1.5 KiB
49 lines
1.5 KiB
import java.util.ArrayList;
|
|
import java.util.Collections;
|
|
import java.util.List;
|
|
|
|
/**
|
|
* 仓库层:封装 List<Article>,对外只暴露安全接口
|
|
* - getAll() 返回不可变视图,切断外部对内部列表的直接引用
|
|
* - add() / addAll() 均进行 null 防御
|
|
*/
|
|
public class ArticleRepository {
|
|
private final List<Article> store = new ArrayList<>();
|
|
|
|
/** 添加单篇文章,忽略 null */
|
|
public void add(Article article) {
|
|
if (article == null) return;
|
|
store.add(article);
|
|
}
|
|
|
|
/**
|
|
* 必做1:addAll —— 批量添加,跳过 null 条目
|
|
* 传入 null 列表本身也安全处理
|
|
*/
|
|
public void addAll(List<Article> articles) {
|
|
if (articles == null) return;
|
|
for (Article a : articles) {
|
|
add(a); // 复用 add() 的 null 防御
|
|
}
|
|
}
|
|
|
|
/** 返回只读视图,防止外部 clear()/add() 破坏内部状态 */
|
|
public List<Article> getAll() {
|
|
return Collections.unmodifiableList(store);
|
|
}
|
|
|
|
/** 按 URL 查找,找不到返回 null */
|
|
public Article findByUrl(String url) {
|
|
if (url == null) return null;
|
|
return store.stream()
|
|
.filter(a -> url.equals(a.getUrl()))
|
|
.findFirst()
|
|
.orElse(null);
|
|
}
|
|
|
|
public int size() { return store.size(); }
|
|
public boolean isEmpty() { return store.isEmpty(); }
|
|
|
|
/** 清空(仅供测试使用) */
|
|
void clear() { store.clear(); }
|
|
}
|
|
|