首页 > 解决方案 > 不可变模式要求

问题描述

我正在使用 java 研究不可变模式,但我无法理解以下两个要求:

  1. 访问属性的实例方法不得更改实例变量
  2. 确保不可变类的构造函数是唯一设置或修改实例变量值的地方。

请有人为第一点举一个简单的例子。对于第二点,我不明白我们如何通过构造函数修改变量,而它们是最终的?

标签: javadesign-patterns

解决方案


这两点或多或少说的是同一件事。它们只是意味着,一旦对象被初始化,就不应更改它。

对于一个真正不可变的对象,那么每个对象都是引用也必须不能被访问器方法修改。例如,String该类由char[]可变的 a 支持。但是,String该类没有公开任何可以让您更改其支持数组内容的方法。因此,String该类可以被认为是不可变的。

关于最终变量——变量必须能够设置在某个地方。拥有一个您根本无法设置的最终变量并没有多大用处。所以构造函数是特殊的,允许设置标记为final的变量。

class StringArrayList {

    // make the variable private, to protect it from being modified from outside the class
    private final String[] arr;

    StringArrayList(int size) {
        // constructors are the only method allowed to set final variables
        arr = new String[size];
    }

    String get(int i) {
        // get method doesn't change the state of the object, so is fine
        // However, if the object returned is mutable then there might be issues.
        return arr[i];
    }

    void set(int i, String item) {
        // set changes the state of arr, and so with this method, StringArrayList cannot 
        // be considered immutable
        arr[i] = item;
    }

}

推荐阅读