根据我对“告诉-不要-询问”原则的理解,我的其他类不应该能够调用存储在任何其他类中的数据。因此,根据这一原则,吸气剂是不受欢迎的。为了防止访问数据,它们通常写为:
class Point {
private final double x;
private final double y;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我要实现诸如两点之间的距离之类的方法,我将需要访问另一个点的 x 和 y。在这种情况下,我需要 getter 方法。
class Point {
private final double x;
private final double y;
Point(double x, double y) {
this.x = x;
this.y = y;
}
private double getX() {
return this.x;
}
private double getY() {
return this.y;
}
public double distanceBetween(Point p) {
double dx = this.x - p.getX();
double dy = this.y - p.getY();
return Math.sqrt(dx * dx + dy * …Run Code Online (Sandbox Code Playgroud)