java学习笔记_不变的对象

不变对象是指在实例化后其外部可见状态无法更改的对象。Java 类库中的 StringIntegerBigDecimal 类就是不变对象的示例 

不变性的长处在于:

1.自由高速的缓存:放在那里几百年不变,不发霉也不生锈,不用担心再拿来用的时候已经不是以前的那个东西了.否则你在存储一个可变对象的引用时,你得考虑一下,会不会有别人会去更改他.

2,固有的线程安全:同时写,或同时写,读才会引起线程问题,既然这个对象不变,写来写去,读来读去都是那样,就不用担心线程问题咯.

3良好的键:不变对象产生最好的 HashMapHashSet 键.连KEY值都被别人给改了.郁闷至死~~~~

如何编写不变的类:

编写不变类很容易。如果以下几点都为真,那么类就是不变的:

  • 它的所有字段都是 final
  • 该类声明为 final
  • 不允许 this 引用在构造期间转义
  • 任何包含对可变对象(如数组、集合或类似 Date 的可变类)引用的字段:
    • 是私有的
    • 从不被返回,也不以其它方式公开给调用程序
    • 是对它们所引用对象的唯一引用
    • 构造后不会更改被引用对象的状态

 对不变对象编码的正确和错误方法

class ImmutableArrayHolder {
  private final int[] theArray;
  // Right way to write a constructor -- copy the array
  public ImmutableArrayHolder(int[] anArray) {
    this.theArray = (int[]) anArray.clone();//使用参数的拷贝,参数就算变了,也没所谓了
  }
  // Wrong way to write a constructor -- copy the reference
  // The caller could change the array after the call to the constructor
  public ImmutableArrayHolder(int[] anArray) {
    this.theArray = anArray;
  }
  // Right way to write an accessor -- don't expose the array reference
  public int getArrayLength() { return theArray.length }
  public int getArray(int n)  { return theArray[n]; }
  // Right way to write an accessor -- use clone()
  public int[] getArray()       { return (int[]) theArray.clone(); }//返回一个拷贝,
哈哈,控制不了我了
  // Wrong way to write an accessor -- expose the array reference
  // A caller could get the array reference and then change the contents
  public int[] getArray()       { return theArray }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值