当前位置: 代码迷 >> java >> 下面是 Java 多重继承设计模式(如果是的话)是哪一个?
  详细解决方案

下面是 Java 多重继承设计模式(如果是的话)是哪一个?

热度:59   发布时间:2023-08-02 10:59:28.0

我已经在 Swing 应用程序中工作了 8 年多,但它可能是 20 年前设计的,设计人员创建了他们自己的定制组件(我认为最初使用 AWT,但在某个阶段更新为 Swing)。

有一个由多个屏幕使用的小部件,它在甘特图栏上显示数据,允许用户交互、拖放等。 此设计的简化描述如下:

//Many lines of implementation code and only 1 constructor
public class GanttChartImplementation extends JPanel {

  public GanttChartImplementation(String p1, Object p2, boolean p3, boolean p4){
    //Implementation code
  }

}


//No implementation only constructors
public class GanttChartInterface extends GanttChartImplementation {

  public GanttChartInterface(String p1, Object p2, boolean p3, boolean p4) {
    super(p1,p2,p3,p4);
  }

  public GanttChartInterface(String p1, Object p2, boolean p3) {
    super(p1,p2,p3,true); //defaults p4 to true as it's not passed in
  }

  public GanttChartInterface(String p1, Object p2) {
    super(p1,p2,true,true); //defaults p3, p4 to true as these are not passed in
  }
}

应用程序中的所有屏幕都将扩展 GanttChartInterface,它的第一个明显用途是从使用甘特图小部件的屏幕隐藏实现类。 即使在理论上,可以更改 GanttChartInterface 以扩展不同的实现类,而无需更改使用甘特图小部件的屏幕。

多年来,我发现这种设计的另一个好处是,当向 GanttChartImplementation 类中的构造函数添加新参数时,不需要更改使用小部件的屏幕,因为只需要修改 GanttChartInterface 中的现有构造函数所以他们将新的参数值设置为默认值,然后将创建一个新的构造函数,示例如下:

//Add new parameter to constructor used to have 4 now 5
public class GanttChartImplementation extends JPanel {

   public GanttChartImplementation(String p1, Object p2, boolean p3, boolean p4, boolean p5){
     //Implementation code
   }

}

只需要修改 GanttChartInterface 即可编译,无需更改任何预先存在的使用小部件的屏幕:

//No implementation only constructors had 3 constructors now has 4
public class GanttChartInterface extends GanttChartImplementation {

  //Create new constructor that receives the new parameter
  public GanttChartInterface(String p1, Object p2, boolean p3, boolean p4, boolean p5) {
    super(p1,p2,p3,p4,p5); 
  }

  public GanttChartInterface(String p1, Object p2, boolean p3, boolean p4) {
    super(p1,p2,p3,p4,true); //defaults p5 to true as it's not passed in
  }

  public GanttChartInterface(String p1, Object p2, boolean p3) {
     super(p1,p2,p3,true,true); //defaults p4, p5 to true as these are not passed in
  }

  public GanttChartInterface(String p1, Object p2) {
     super(p1,p2,true,true,true); //defaults p3, p4, p5 to true as these are not passed in
  }
}

我已经查看了许多关于网络和 SO 问题的文章,这似乎不是 GoF 设计模式,如果这是一种广泛使用的设计模式,我还没有找到任何地方? 我正在尝试查找信息,因为我想知道是谁提出了这个设计。 预先感谢您的任何帮助。

在 OOP 中,它是一个提供默认值的重载构造函数。

编辑就像评论中提到的@boris。 您不需要使用子类来重载方法,您只需在 GanttChartImplementation 中即可完成。 这里没有继承的好处。 只是不必要的课程。

  相关解决方案