java - 两个 Java 相关类的最佳实践,例如 Recipe 和 Ingredient
问题描述
我有两个类食谱和成分(带有:成分名称,数量,单位)和两种连接这两个类的方法。
- 一个Recipe 对象包含一个成分对象列表(List 或ArrayList)。
- 成分对象包含相关配方对象的 id。
考虑到我需要在应用程序中找出哪些食谱对象包含特定成分这一事实,哪一个是性能的最佳实践。
非常感谢您!
解决方案
为了允许 aRecipe
将成分类型与该成分的数量分开引用,我建议创建一个Ingredient
类和一个IngredientQuantity
类。
该类Ingredient
代表一种成分,不知道数量。作为一个简单的起点,Ingredient
该类可能仅包含一个String
包含成分名称的 a,但您可以添加其他字段来表示有关此成分类型的其他有用数据。稍后我们需要将此类Ingredient
用作键Map
,因此请确保覆盖类中的equals()
andhashCode()
方法Ingredient
,否则它将无法用作键。
该类IngredientQuantity
代表特定数量的特定成分,其轮廓可能如下所示:
public final class IngredientQuantity {
public static enum QuantityUnit {
// Add other unit types here.
PIECE, MILLILITRE, GRAMME
}
private final Ingredient ingredient;
private final QuantityUnit unit;
private final double quantity;
public IngredientQuantity(Ingredient ingredient, QuantityUnit unit,
double quantity) {
this.ingredient = Objects.requireNonNull(ingredient);
this.unit = Objects.requireNonNull(unit);
this.quantity = quantity;
if (quantity < 0) {
throw new IllegalArgumentException("Quantity cannot be negative.");
}
}
}
(这已被简化,因此您必须添加 getter 方法和其他必需的功能。)
现在你的Recipe
类可以包含一个Collection<IngredientQuantity>
描述配方所需的每种成分的数量。如果您需要偏执于只允许每种成分类型一次,那么您可以使用 aMap<Ingredient, IngredientQuantity>
来检测重复项。但是,如果您可以控制构建食谱对象,那么无论如何您都应该能够避免重复。
无论哪种方式,您现在都可以从 a 获取所需的对象Recipe
集合。Ingredient
Ingredient
为了得到Recipe
你需要建立一个Map<Ingredient, Set<Recipe>>
从每个Ingredient
对象到Recipe
需要该成分类型的所有对象的映射。当您将配方读入应用程序时,您需要填充它,遍历每个配方的成分,然后将其添加Recipe
到地图中Ingredient
键下的地图中。
如果您的应用程序有大量配方,以至于它无法在应用程序启动时读取所有配方,那么您必须将映射数据与配方数据一起存储,例如在数据库中或数据文件结构本身。但这是一个非常不同的问题。
推荐阅读
- r - 如何删除数据框中的孩子的孩子以在 R 中绘制网络?
- java - Android UpdateManager 问题 - 并非所有设备都能获得更新信息
- python - Pandas 引用了哪些项目?
- haskell - windows上的haskell STACK BUILD给出权限错误(重命名)
- python - 如何删除出现在另一个列表中的列表列表的元素
- backup - H2 数据库:如何解锁数据库文件以进行备份?
- spring - 如何从 SqlExceptionHelper 获取有关 REST spring 应用程序的错误信息
- python - Python Kivy:更新标签
- python - 如何在 Qlabel 中的图像顶部从 MouseEvents 绘制多边形
- python-3.7 - python37:@dataset 是否调用 super.__init__(...)?