我正在学习不可变对象(immutable对象)。我必须让下面的类(class)不可变。我做对了吗?
import java.awt.Point;
public class MyImmutablePoint {
Point point;
public MyImmutablePoint(Point point) {
super();
this.point = point;
}
public MyImmutablePoint() {
this (new Point (0,0));
}
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point
}
}
“不可变”类:
public final class MyImmutablePoint {
private final Point point;
public MyImmutablePoint(Point point) {
this.point = point;
}
public MyImmutablePoint() {
this (new Point (0,0));
}
public Point getPoint() {
return point;
}
}
虽然我不确定 toString
方法。
也许返回一个像 Point 这样的对象也可以像数组一样被修改,但不确定
最佳答案
没有
final Point p = new Point(0,0);
final ImmutablePoint ip = new ImmutablePoint(p);
两个例子:
//change the original Point passed in
p.x = 10
//use the getter and change the Point
ip.getPoint().x = 10
因此,首先您需要创建构造函数中获取的Point
的防御副本:
public MyImmutablePoint(Point point) {
this.point = new Point(point);
}
然后您需要创建从 getter 返回的 Point
的防御副本:
public Point getPoint() {
return new Point(point);
}
这一切让我建议最好不要暴露内部 point
:
public final class MyImmutablePoint {
private final Point point;
public MyImmutablePoint(Point point) {
this.point = new Point(point);
}
public MyImmutablePoint() {
this.point = new Point (0,0);
}
public int getX() {
return point.x;
}
public int getY() {
return point.y;
}
}
进一步格式化您的代码并订购您的成员。
关于java - 使类不可变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34176732/