Java 设计一个收藏的功能
时间: 2024-03-11 14:49:48 浏览: 73
好的,我可以为您提供一个简单的 Java 收藏功能的设计示例。
首先,我们需要创建一个 Product 类来表示产品,包含产品ID、名称、描述等基本信息:
```
public class Product {
private int id;
private String name;
private String description;
public Product(int id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
// Getters and setters
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
}
```
接下来,我们创建一个 User 类来表示用户,包含用户ID、用户名等基本信息:
```
public class User {
private int id;
private String username;
public User(int id, String username) {
this.id = id;
this.username = username;
}
// Getters and setters
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
}
```
然后,我们创建一个 ProductFavorite 类来表示收藏,包含用户、产品以及收藏时间等信息:
```
public class ProductFavorite {
private User user;
private Product product;
private LocalDate favoriteDate;
public ProductFavorite(User user, Product product, LocalDate favoriteDate) {
this.user = user;
this.product = product;
this.favoriteDate = favoriteDate;
}
// Getters and setters
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
public Product getProduct() { return product; }
public void setProduct(Product product) { this.product = product; }
public LocalDate getFavoriteDate() { return favoriteDate; }
public void setFavoriteDate(LocalDate favoriteDate) { this.favoriteDate = favoriteDate; }
}
```
最后,我们创建一个 ProductFavoriteService 类来处理收藏的逻辑,包含添加收藏、取消收藏等方法:
```
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class ProductFavoriteService {
private List<ProductFavorite> favorites = new ArrayList<>();
// 添加收藏
public void addFavorite(User user, Product product) {
LocalDate favoriteDate = LocalDate.now();
ProductFavorite favorite = new ProductFavorite(user, product, favoriteDate);
favorites.add(favorite);
}
// 取消收藏
public void removeFavorite(User user, Product product) {
favorites.removeIf(favorite -> favorite.getUser().equals(user) && favorite.getProduct().equals(product));
}
// 获取用户收藏的产品列表
public List<Product> getFavoriteProducts(User user) {
List<Product> favoriteProducts = new ArrayList<>();
for (ProductFavorite favorite : favorites) {
if (favorite.getUser().equals(user)) {
favoriteProducts.add(favorite.getProduct());
}
}
return favoriteProducts;
}
}
```
这里我们使用了一个 List 来存储所有的收藏记录,并提供了添加收藏、取消收藏和获取用户收藏的产品列表的方法。您可以根据自己的需求来扩展这个类。
阅读全文