处理重复方法 Headers

Dealing with Duplicate Method Headers

我是编码新手,所以让我们解决这个问题。另外,我目前正在使用 Java。 我想用两种不同的方式实例化一条线 object:

public Line(double x1, double y1, double x2, double y2){}//creates a line connecting two points

public Line(double x, double y, double dir, double length){}//creates a line extending off of one point

但是,根据编译器,它们都具有相同的方法header。

我考虑过向第二个构造函数添加一个无用的参数,但这看起来很乱而且没有必要。有没有人对现在和将来如何处理这样的问题有什么建议?

注意:本主题只是关于修复 header,而不是关于如何改进我的代码。谢谢!

您可以为这两个构造函数调用创建两个不同的静态工厂方法。 根据维基百科:

The Factory Method design pattern is one of the "Gang of Four" design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.

The Factory Method design pattern is used instead of the regular class constructor for keeping within the SOLID principles of programming, decoupling the construction of objects from the objects themselves

工厂方法本质上只是方法,可以具有不同的名称(并且不必使用 class 的名称)和不同数量的参数,甚至与前一个参数数量相同。你可以这样做:

public static Line createJoining(double x1, double y1, double x2, double y2){...}
public static Line createExtending(double x1, double y1, double x2, double y2){...}

那么你可以有一个像这样的构造函数

public Line(double x1, double y1, double x2, double y2){}//creates a line connecting two points

createJoining()createExtending() 中,您可以调用此构造函数, 并将您不同的程序逻辑放入这两个工厂方法中。

createJoining()createExtending(),必须 return 的新实例行是这样的:

public static Line createJoining(double x1, double y1, double x2, double y2){
  // program logic goes here, where you can do some calculations

   return new Line(x1, y1, x2, y2);
}

public static Line createExtending(double x1, double y1, double x2, double y2){
// program logic goes here, where you can do some calculations

   return new Line(x1, y1, x2, y2);
}

用法示例,

Line joinedLine = Line.createJoining(0.1, 3.5, 10.5, 1.0);
Line extendedLine = Line.createExtended(0.6, 29.4, 20.0, 2.0);

More info about Factory Methods here

另一种方法是避免相同的方法头,同时使用更有意义的参数类型:

import java.awt.geom.Point2D;
…
        public Line(Point2D.Double p1, Point2D.Double p2) { … }

        public Line(Point2D.Double p, double dir, double length) { … }