带有枚举的Java层次结构

时间:2014-01-08 15:13:59

标签: java

我有一个类别列表,其中一些有子类别。我需要使用枚举来实现此层次结构。 我这样做了:

  public enum Type {
   Category1(1, new LinkedHashMap<Integer, String>()),
   Category2(2, getSubcategory2()),
    Category3(3, getSubcategory3());

    private final int id;
   private final Map<Integer, String> subcategories;


    Type(int id, Map<Integer, String subcategories) {
    this.id = id;
    this.subcategories = subcategories;
    }

    public int getId() {
    return id;
    }

    public Map<Integer, String> getSubcategories() {
    return subcategories;
    }
    }

我想要一个更优雅的解决方案,因为在这个时刻,如果我想看一个类别是否有子类别我必须每次验证subategories.size()&gt; 0

1 个答案:

答案 0 :(得分:4)

public enum Category {
    CATEGORY_1(null),
        CATEGORY_1_1(CATEGORY_1),
        CATEGORY_1_2(CATEGORY_1),

    CATEGORY_2(null),
        CATEGORY_2_1(CATEGORY_2),
            CATEGORY_2_1_1(CATEGORY_2_1),
            CATEGORY_2_1_2(CATEGORY_2_1);

    private final Category parent;
    private final List<Category> children = new ArrayList<>();
    private final List<Category> roChildren = Collections.unmodifiableList(children);

    private Category(Category parent) {
        this.parent = parent;
        if (parent != null) {
            parent.children.add(this);
        }
    }

    public Category getParent() {
        return parent;
    }

    public List<Category> getChildren() {
        return roChildren;
    }
}