首页 > 解决方案 > 两个 Java 相关类的最佳实践,例如 Recipe 和 Ingredient

问题描述

我有两个类食谱和成分(带有:成分名称,数量,单位)和两种连接这两个类的方法。

  1. 一个Recipe 对象包含一个成分对象列表(List 或ArrayList)。
  2. 成分对象包含相关配方对象的 id。

考虑到我需要在应用程序中找出哪些食谱对象包含特定成分这一事实,哪一个是性能的最佳实践。

非常感谢您!

标签: javaclass

解决方案


为了允许 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键下的地图中。

如果您的应用程序有大量配方,以至于它无法在应用程序启动时读取所有配方,那么您必须将映射数据与配方数据一起存储,例如在数据库中或数据文件结构本身。但这是一个非常不同的问题。


推荐阅读