不可变对象

不可变对象(Immutable Object):对象一旦被创建后,对象所有的状态及属性在其生命周期内不会发生任何变化。

  • 一旦创建,这个对象(状态/值)不能被更改了。
  • 其内在成员变量的值就不能修改了。
  • 典型的不可变对象
    1.八个基本型别的包装类的对象
    2.String,BigInteger等的对象
public class ImmutableObject {
    private int value;
     
    public ImmutableObject(int value) {
        this.value = value;
    }
     
    public int getValue() {
        return this.value;
    }
}

由于ImmutableObject不提供任何setter方法,并且成员变量value是基本数据类型,getter方法返回的是value的拷贝,所以一旦ImmutableObject实例被创建后,该实例的状态无法再进行更改,因此该类具备不可变性。

不可变对象之间也是传指针(引用)。

比如我们平时用的最多的String:

public class Test {
 
    public static void main(String[] args) {
        String str = "I love java";
        String str1 = str;
 
        System.out.println("after replace str:" + str.replace("java", "Java"));
        System.out.println("after replace str1:" + str1);
    }
}

输出结果:

从输出结果可以看出,在对str进行了字符串替换替换之后,str1指向的字符串对象仍然没有发生变化。

如何创建不可变对象

  • 所有的属性都是final和private的。
  • 不提供setter方法。
  • 类是final的,或者所有的方法都是final。

不可变对象优点:

  • 只读,线程安全
  • 并发读,提高性能
  • 可以重复使用

缺点:

  • 制造垃圾,浪费空间.