I have a class Product. Each product can have any amount of Categories:
public class Product
{
private List<Category> categories
...
}
Each Category has its own unique set of subcategories. For example:
- Category 'Red' has subcategories 'Maroon', 'Orange', 'Bordeaux'
- Category 'Blue' has subcategories 'Light', 'Dark', 'Azure'
For each set of subcategories, I created an enum with possible static values:
public enum RedSubCategory
{
MAROON, ORANGE, BORDEAUX;
}
public enum BlueSubCategory
{
LIGHT, DARK, AZURE;
}
I'm now struggling with creating the Category class. Because each category is well defined, I thought of making it an enum. However, each enum value should have a list of subcategories of a different sub-type and this won't work:
public enum Category
{
RED, BLUE;
private List<SubCategory> subCategories;
// This won't work! SubCategory is not a real class and the
// SubCategory enums can't extend from a common supertype!
public setSubCategories(List<SubCategory> subCategories)
{
this.subCategories : subCategories;
}
}
I run into the same problem if I make Category a class instead of an enum. I can solve this using generics, but I lose the static definition of all possible categories. Additionally, how do I make it so the category RED is the only category that can use RedSubCategories? By using a class with generics, nothing would stop me from making a category object with category "blue" and red subcategories!
Are there any patters or inheritance/generics tricks I can use here?