简体   繁体   中英

Java Class/Inheritance Structuring

So I'm trying to determine/remember what type of interface/abstract I have to use to get this layout to do what I want. I have two types of objects:

Widget and ComboWidget. I want both of these to be implemented in other classes. As the name suggests, ComboWidget is a base class that will be comprised of multiple Widget objects. I also want to have some boilerplate functionality such as addWidget(), removeWidget(), listWigets(), etc that will be applied to all items that implement ComboWidget.

Widget itself will do the same as it will be implemented by specific instances of widgets (A button widget, a fillbar widget etc).

I want to be able to have a panel or table that the user can add any widget or combo widget. So for said panel I want to generically refer to the Widget or ComboWidget as just Widget class and it will allow either or, in addition to any other object that implements those. What is the best way to accomplish this?

Best way to explain this is a drawing of sorts:

Widget 
     |_ ComboWidget
                  |_ TableComboWidget
                  |_ BoomHeightComboWidget
     |_ ButtonWidget
     |_ FillBarWiget
     |_ TextWidget

I want to be able to make a function that says addWidget(Widget) and any of the above can be placed as an argument. (Except Widget and ComboWidget themselves as they will likely be the interface/abstracts)

What you have just described seems a lot like a Composite Pattern

And I don't see anything wrong with your class layout. Your addWigget method should work just as you described it.

Study the Java AWT class hierarchy . It has the structure that you are looking for - the Component class serves as the base class of every AWT component, and Container is the equivalent of your ComboWidget .

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