简体   繁体   中英

How to represent a multilevel hierarchy in Java

I am trying to make an Android application where you can buy and sell items. 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; 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. That way you can assemble trees of categories to your heart's content by adding instances and data rather than new classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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