没有可变引用的示例
public final class Color { final private int red; final private int green; final private int blue; private void check(int red, int green, int blue) { if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255) { throw new IllegalArgumentException(); } } public Color(int red, int green, int blue) { check(red, green, blue); this.red = red; this.green = green; this.blue = blue; } public Color invert() { return new Color(255 - red, 255 - green, 255 - blue); } }
不可变类(Immutable)的优势是什么?
不变性的优点是并发性。在可变对象中很难保持正确性,因为多个线程可能试图更改同一对象的状态,导致一些线程看到同一对象的不同状态,这取决于对所述对象的读写时间。
通过具有不可变的对象,可以确保查看对象的所有线程都会看到相同的状态,因为不可变对象的状态不会改变。
定义不可变类的规则
以下规则定义了创建不可变量的简单策略。
- 不要提供“Setter”方法 - 修改字段引用的字段或者对象的方法。
- 使所有领域最终和私有。
- 不要允许子类覆盖方法。最简单的方法是将类作为最终声明。一种更复杂的方法是使构造函数私有和构建工厂方法中的实例。
- 如果实例字段包含对可变对象的引用,则不允许更改这些对象:
- 不要提供修改可变对象的方法。
- 不要与可变对象共享引用。切勿将引用存储到构造函数的外部可变对象;如有必要,请创建副本并存储对副本的引用。同样,必要时创建内部可变对象的副本,以避免在方法中返回原件。
使用可变引用的示例
在这种情况下,类点是可变的,有些用户可以修改此类的对象状态。
class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } } //… public final class ImmutableCircle { private final Point center; private final double radius; public ImmutableCircle(Point center, double radius) { //我们在这里创建新对象,因为它不应该被更改 this.center = new Point(center.getX(), center.getY()); this.radius = radius; }
不可变量的对象是状态在初始化之后状态不会改变的实例。
例如,字符串是一个不可变类,并且一旦实例化其值永远不会改变。
日期:2020-06-02 22:15:19 来源:oir作者:oir