I have a class like:
public class Food
{
public static IList<Ingredient> ingredients
public bool uses(Ingredient i)
{
return ingredients.Contains(i);
}
}
Then I inherit from it to make various kinds of food like:
public class Cake : public Food
{
public static IList<Ingredient> ingredients = new List<Ingredient>()
{
Sugar,
Eggs,
Milk
}
}
Now I want to be able to do
Food f = getFood();
if (f.uses(Eggs))
{
// Do something
}
So I want to have a static list of ingredients that (for example) all cakes can share, rather than a list per instance of Cake and be able to access it in a virtual way.
I’m willing to stir the code around to get a similar effect if needed!
In such cases, the OOD “prefer” to make the class
Foodabstract, since the “Ingredients” will be different from aFoodto another. Thus, as others have pointed out, making this liststaticis meaningless, sincestaticshould be a modifier to an attribute which is not differentiating by the objects.I suggest a solution as follows:
Now any class – to be a concrete – will be driven from
Foodand therefore it must implement this property so that it gives its owningredients: