package com.example.testenum;
import java.util.Random;
/**
* Created by admin on 2018/6/5.
* 通过这种方式很方便组织上述情景,同时确保每种具体类型的食物也属于Food
* ,现在我们利用一个枚举嵌套枚举的方式把前面定义的菜谱放到一个Meal菜单中,
* 通过这种方式就可以同意管理菜单的数据了。
*/
public enum MealEnum {
APPETIZER(Food.Appetizer.class),
MAINCOURSE(Food.MainCourse.class),
DESSERT(Food.Dessert.class),
COFFEE(Food.Coffee.class);
private Food[] values;
MealEnum(Class<? extends Food> kind){
//通过class对象获取枚举实例
values = kind.getEnumConstants();
System.out.println("values:"+values.getClass().getSimpleName());
}
interface Food {
enum Appetizer implements Food {
SALAD, SOUP, SPRING_ROLLS;
}
enum MainCourse implements Food {
LASAGNE, BURRITO, PAD_THAI,
LENTILS, HUMMOUS, VINDALOO;
}
enum Dessert implements Food {
TIRAMISU, GELATO, BLACK_FOREST_CAKE,
FRUIT, CREME_CARAMEL;
}
enum Coffee implements Food {
BLACK_COFFEE, DECAF_COFFEE, ESPRESSO,
LATTE, CAPPUCCINO, TEA, HERB_TEA;
}
}
public Food randomSelection() {
return Enums.random(values);
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
for (MealEnum meal : MealEnum.values()) {
Food food = meal.randomSelection();
System.out.println(food);
}
System.out.println("---");
}
}
}
/**
* Created by admin on 2018/6/5.
*/
public class Enums {
private static Random rand = new Random(47);
public static <T> T random(T[] values){
return values[rand.nextInt(values.length)];
}
}
网友评论