我正在学习不可变的对象.我必须使下面的类不可变.我做得对吗?
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); }
然后你需要创建一个Point
从getter返回的防御副本:
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; } }
进一步格式化您的代码并订购您的成员.
不,它不是一成不变的.Point仍然可以由MyImmutablePoint的创建者修改.例如:
Point point = new Point(1, 1); MyImmutablePoint immutablePoint = new MyImmutablePoint(point); point.setLocation(0, 0);