保护性拷贝:在对资源进行操作时,不对操作资源本身进行修改,而是对资源内容进行复制,通过创建副本对象来避免共享安全问题.
以java中String对象为例:
不可变类条件:类、类中所有属性都是 final 的,保证了属性是只读的,不能修改,保证了该类中的方法不能被覆盖,防止子类无意间破坏不可变性.
String类中如何保证通过保护性拷贝实现不可变的?
以substring方法为例(其他操作原理相同):
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
调用构造方法:new String(value, beginIndex, subLen)重新创建了一个Stringl类.
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count <= 0) {
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
if (offset <= value.length) {
this.value = "".value;
return;
}
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = Arrays.copyOfRange(value, offset, offset+count);
}
对于新创建的String中value属性也是按照条件复制原来的值返回新的char数组.所以保证了不可变性,在不改变原来的值的情况下保证共享安全问题.