Java不可变类? [英] Java immutable classes?

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

问题描述

我找到了文章使用一段有趣的代码:

I found an article with an interesting piece of code:

public class Employee {

    private String firstName;
    private String lastName;

    //private default constructor
    private Employee(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public static Employee valueOf (String firstName, String lastName) {
        return new Employee(firstName, lastName);
    }
}

我真的好奇了解创造这个的好处那种课。
我明白这个类的对象是不可变的,因为一旦初始化就无法改变它的变量值。我之前从未做过这样的事情,我真的不明白它的优点。

I am really curious in understanding the advantage of creating this kind of classes. I understand that here that an object of this class would be immutable, because there is no way of changing its variable values once initialized. I never did something like this before, and i dont really understand the advantage of it.


  • 为什么这是一个好习惯?

  • 你能说出一种情况,这个方法可以是用过吗?

  • 常量或只读变量怎么样?是不是很相似?

  • 在文章中说,这对应用程序的性能不利。 但为什么

  • Why is it a good practice?
  • Could you name a situation where this approach can be used?
  • What about constants or read only variables? Is not that very similar?
  • In the article says, that this is not good for the performance of the application. But why?

推荐答案

您提到的示例是不可改变的对象。它在编程语言中广泛使用的概念。

The example you have mentioned is of an Immutable Objects. Its widely used concepts in programming languages.

从上面的链接引用。优点是

Quoting from the link above. The advantages are


  • 构造,测试和使用都很简单

  • 是自动线程安全的并且没有同步问题

  • 不需要复制构造函数

  • 不需要克隆的实现

  • 允许hashCode使用延迟初始化,并缓存其返回值

  • 当用作字段时不需要防御性地复制

  • make good地图键和设置元素(这些对象在集合中不得更改状态)

  • 在构造时建立一次类不变量,并且永远不需要再次检查

  • 总是有失败原子性(Joshua Bloch使用的术语):如果一个不可变对象 - 抛出异常,它永远不会处于不受欢迎或不确定的状态

  • are simple to construct, test, and use
  • are automatically thread-safe and have no synchronization issues
  • do not need a copy constructor
  • do not need an implementation of clone
  • allow hashCode to use lazy initialization, and to cache its return value
  • do not need to be copied defensively when used as a field
  • make good Map keys and Set elements (these objects must not change state while in the collection)
  • have their class invariant established once upon construction, and it never needs to be checked again
  • always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object - throws an exception, it's never left in an undesirable or indeterminate state

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

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