在 Java 中"enum inheritance"的解决方法实现?



前言:我已经研究过为什么">枚举继承";在Java中是非法的。

我的问题如下:给定一个类Recipe,我希望它的属性category是一个常量值列表,比如APPETIZER, BREAKFAST, DESSERT, MAIN_COURSE, SOUP——我在逻辑上使用枚举。

我的问题是:如果我希望每个枚举都有";他们自己的孩子";(例如:BREAKFASTSWEETSAVORYDESSERTCAKEMUFFINBISCUITS(,因此:

  1. 指定子类别("子枚举"(是强制(例如myRecipe.setCategory(DESSERT)应引发异常(
  2. 使用";子枚举";来自不同的";家庭;被禁止(例如SOUP.BISCUITS应引发异常(
  3. 我应该能够访问";子枚举";通过点表示法(例如myRecipe.setCategory(DESSERT.CAKE)(-或其它类似的"点">轻量级";语法

我还没能在Java中找到任何干净的解决方案来满足这三个必要条件。

有没有";深奥的";设计模式?你将如何实现这一点?

您可以这样做:

class Recipe {
private final Meal meal;
private final MealCategory category;
public <T extends Meal> Recipe(T meal, MealCategory<T> category) {
this.meal = meal;
this.category = category;
}
}
abstract class Meal {}
class Breakfast extends Meal {}
class Dinner extends Meal {}
class MealCategory<T extends Meal> {}
class Cereal extends MealCategory<Breakfast> {}
class Meat extends MealCategory<Dinner> {}
public class Test {
public static void main(String[] args) {
Recipe r = new Recipe(new Breakfast(), new Cereal());
Recipe r2 = new Recipe(new Breakfast(), new Meat()); // compile time error
}
}

简单设计

创建一个类Category。在Category内部,声明所有枚举类。

public class Category
{
public enum APPETIZER
{
}
public enum BREAKFAST
{
SWEET,
SAVORY
}
public enum DESSERT
{
CAKE,
MUFFIN,
BISCUITS
}
public enum MAIN_COURSE
{
}
}

Recipe类中,类别的类型应为DESSERT。我有静态导入的Category类。

public class Recipe
{
DESSERT category;
public void setCategory(DESSERT category)
{
this.category = category;
}
public static void main(String[] args)
{
Recipe myRecipe = new Recipe();
myRecipe.setCategory(DESSERT.BISCUITS);
// statements below give compile time errors
// myRecipe.setCategory(DESSERT);
// myRecipe.setCategory(BREAKFAST.SWEET);
}
}

改进

类别转换为标记界面。DESSERTBREAKFAST等所有类别都应实现Category。

interface Category {}
enum APPETIZER implements Category 
{
}
enum BREAKFAST implements Category
{
SWEET,
SAVORY
}
enum DESSERT implements Category
{
CAKE,
MUFFIN,
BISCUITS
}
enum MAIN_COURSE implements Category
{
}

使配方通用。

public class Recipe <T extends Category>
{
T category;
public void setCategory(T category)
{
this.category = category;
}
public static void main(String[] args)
{
Recipe<DESSERT> myRecipe = new Recipe<>();
myRecipe.setCategory(DESSERT.BISCUITS);
// statements below give compile time errors
// myRecipe.setCategory(DESSERT);
// myRecipe.setCategory(BREAKFAST.SWEET);
}
}

这些不是设计模式。它们是自我实现的。

最新更新