简体   繁体   English

如何在 Java 中表示多级层次结构

[英]How to represent a multilevel hierarchy in Java

I am trying to make an Android application where you can buy and sell items.我正在尝试制作一个 Android 应用程序,您可以在其中买卖商品。 I've run into a wall: I am stuck at how to represent categories and sub-categories.我遇到了一堵墙:我被困在如何表示类别和子类别上。 Any category can have some number of sub-categories, and these sub-categories can also have sub categories with fields in them, etc.任何类别都可以有一定数量的子类别,这些子类别也可以包含带有字段的子类别,等等。

For instance, let's say you want to sell a pair of your watches, the category and sub categories might be:例如,假设您想出售一对手表,类别和子类别可能是:

-Jewelry
--Men
---Watches
----Rolex

or it might even be或者它甚至可能是

-Jewelry
--Men
---Watches
----Rolex
-----Models
------SubMarine

How would you represent this with a class hierarchy?您将如何用类层次结构表示这一点? I can't seem to find a solution that doesn't end out with a ton of classes and something that is difficult to update.我似乎找不到一个解决方案,它不会以大量的类和难以更新的东西结束。

I was thinking of using Jackson/Gson, Mysql/MSSQL for storage and most likely rest services for saving it;我正在考虑使用 Jackson/Gson、Mysql/MSSQL 进行存储和最有可能的休息服务来保存它; bonus points for an answer that can integrate with those technologies.可以与这些技术集成的答案的奖励积分。

Inheritance would be a naive approach.继承将是一种幼稚的方法。 A sub-class per Category and Subcategory cannot scale.每个类别和子类别的子类不能扩展。

What about sub-sub-categories?子类别呢? Oh, my.天啊。

Maybe a better approach is to stick with a Category class and make it a Composite , or just create a tree of Category instances.也许更好的方法是坚持使用Category类并使其成为Composite ,或者只是创建一个Category实例树。 That way you can assemble trees of categories to your heart's content by adding instances and data rather than new classes.通过这种方式,您可以通过添加实例和数据而不是新类来将类别树组合到您的心目中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM