简体   繁体   English

Java类/继承结构

[英]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. Widget和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. 顾名思义,ComboWidget是一个基类,它将由多个Widget对象组成。 I also want to have some boilerplate functionality such as addWidget(), removeWidget(), listWigets(), etc that will be applied to all items that implement ComboWidget. 我还希望具有一些样板功能,例如addWidget(),removeWidget(),listWigets()等,这些功能将应用于实现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. 因此,对于上述面板,我想将Widget或ComboWidget统称为Widget类,除了实现这些对象的任何其他对象外,它还将允许或。 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. 我希望能够制作一个说addWidget(Widget)的函数,并且以上任何内容都可以作为参数放置。 (Except Widget and ComboWidget themselves as they will likely be the interface/abstracts) (Widget和ComboWidget本身除外,因为它们很可能是界面/抽象)

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. 您的addWigget方法应该像您描述的那样工作。

Study the Java AWT class hierarchy . 研究Java AWT类的层次结构 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 . 它有您正在寻找的结构- Component类作为基类中的每个AWT组件,而Container是你相当于ComboWidget

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

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