当前位置:  开发笔记 > 编程语言 > 正文

使一个类不变

如何解决《使一个类不变》经验,为你挑选了2个好方法。

我正在学习不可变的对象.我必须使下面的类不可变.我做得对吗?

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这样的对象也可以像数组一样修改但不确定



1> Boris the Sp..:
没有
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;
    }
}

进一步格式化您的代码订购您的成员.



2> why_vincent..:

不,它不是一成不变的.Point仍然可以由MyImmutablePoint的创建者修改.例如:

    Point point = new Point(1, 1);
    MyImmutablePoint immutablePoint = new MyImmutablePoint(point);
    point.setLocation(0, 0);

推荐阅读
ar_wen2402851455
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有