使对象不可变的可能方法 [英] Possible ways of making an Object immutable

查看:103
本文介绍了使对象不可变的可能方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种有效的方法来构建一个不可变的类,就像Java的String类一样。

I am looking for some efficient way for building a immutable class, just like Java's String class.

推荐答案


  1. 所有字段必须为
    private ,最好是 final

  2. 确保类不能被
    重写 - 使类最终,
    或使用静态工厂并保持
    构造函数私有

  3. 字段必须是从
    构造函数/工厂填充

  4. 不为
    字段提供任何设置器

  5. 注意集合。使用
    Collections.unmodifiable * 。此外,集合应仅包含不可变对象

  6. 所有getter必须提供
    不可变对象或使用防御性复制

  7. 不提供
    更改$ b内部状态的任何方法$ b Object。

  1. All the fields must be private and preferably final
  2. Ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private
  3. Fields must be populated from the Constructor/Factory
  4. Don't provide any setters for the fields
  5. Watch out for collections. Use Collections.unmodifiable*. Also, collections should contain only immutable Objects
  6. All the getters must provide immutable objects or use defensive copying
  7. Don't provide any methods that change the internal state of the Object.

Tom Hawtin 指出 final 可以是可选的。 字符串 class 只有一个缓存 hash var调用哈希函数时。

Tom Hawtin pointed out that final can be optional. String class has a cache hash var that is only assigned when the hash function is called.

这篇关于使对象不可变的可能方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆