0

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)

3
  • Think of furniture and chair. Furniture is general and chair is specific. You can't create a "furniture" but you can create a chair. Similarly, it looks like you can't create a Widget but you can create a ButtonWidget. Therefore Widget should be abstract, no? Commented Mar 29, 2019 at 14:10
  • Yes, but remind me, can you have boiler plate code in an abstract class? Commented Mar 29, 2019 at 14:13
  • An abstract, base class is intended for containing code common to all subclasses, for example each Widget has a screen location. Hence class Widget would have a data member storing that information. Commented Mar 29, 2019 at 14:16

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. But should Widget / Combo Widget be Interfaces or Abstract Classes? How should ComboWidget extend off of Widget to achieve this result?
Both should be abstract classes.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.