定义不可变对象的策略

以下规则定义了创建不可变对象的简单策略。并非所有记录为“不可变”的类都遵循这些规则。这并不一定意味着这些类的创建者是草率的-他们可能有充分的理由相信,这些类的实例在构造之后不会改变。但是,此类策略需要复杂的分析,并不适合 Starters。

  • 不要提供“ setter”方法-修改字段或字段引用的对象的方法。

  • 将所有字段设为finalprivate

  • 不允许子类覆盖方法。最简单的方法是将类声明为final。一种更复杂的方法是使构造函数private并在工厂方法中构造实例。

  • 如果实例字段包含对可变对象的引用,则不允许更改这些对象:

  • 不要提供修改可变对象的方法。

  • 不要共享对可变对象的引用。永远不要存储对传递给构造函数的外部可变对象的引用;如有必要,请创建副本,并存储对副本的引用。同样,在必要时创建内部可变对象的副本,以避免在方法中返回原始对象。

将此策略应用于SynchronizedRGB将导致以下步骤:

  • 此类中有两种设置方法。第一个set任意转换对象,并且在类的不可变版本中没有位置。第二个参数invert可以通过使其创建一个新对象而不是修改现有对象来进行修改。

  • 所有字段已经是private;他们被进一步限定为final

  • 该类本身被声明为final

  • 只有一个字段引用一个对象,而该对象本身是不可变的。因此,没有必要采取措施来防止更改“包含”的可变对象的状态。

完成这些更改后,我们有了ImmutableRGB

final public class ImmutableRGB {

    // Values must be between 0 and 255.
    final private int red;
    final private int green;
    final private int blue;
    final private String name;

    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 ImmutableRGB(int red,
                        int green,
                        int blue,
                        String name) {
        check(red, green, blue);
        this.red = red;
        this.green = green;
        this.blue = blue;
        this.name = name;
    }

    public int getRGB() {
        return ((red << 16) | (green << 8) | blue);
    }

    public String getName() {
        return name;
    }

    public ImmutableRGB invert() {
        return new ImmutableRGB(255 - red,
                       255 - green,
                       255 - blue,
                       "Inverse of " + name);
    }
}